﻿using Abp.Data;
using Abp.Application.Services;
using Abp.EntityFrameworkCore;
using JYJ.AiYard.Database;
using JYJ.AiYard.EntityFrameworkCore.Repositories;
using JYJ.AiYard.StationManagement.TbYardIssuedCards;
using JYJ.AiYard.StationManagement.TbYardParamsSets;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using System.Reflection;
using Abp.Logging;
using JYJ.AiYard.StationManagement.TbClientRegisters;
using JYJ.AiYard.StationManagement.TbDiscountBills;
using JYJ.AiYard.StationManagement.TbObjects;
using JYJ.AiYard.StationManagement.TbSales;
using JYJ.AiYard.StationManagement.TbStationParams;
using JYJ.AiYard.StationManagement.TbYardBlackLists;
using JYJ.AiYard.StationManagement.TbYardLovingLists;
using JYJ.AiYard.StationManagement.TbYardUserParkings;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.TbStations;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using JYJ.AiYard.StationManagement.TbYardMonthCardOnlines;
using JYJ.AiYard.StationManagement.YardCommonHald;
using Abp.Extensions;
using JetBrains.Annotations;
using JYJ.AiYard.StationManagement.TbYardPayMonthCards;
using JYJ.AiYard.StationManagement.TvDigitalPay;
using AiYard.Common;
//using JYJ.AiYard.StationManagement.tVDIGITALPAYs;

namespace JYJ.AiYard.EntityFrameworkCore
{
    public class AiYardDbTableIssuedCard : RepositoryAndSqlHelper<TbYardIssuedCardDb, long>, IAiYardDbTableIssuedCard
    {

        public AiYardDbTableIssuedCard(IDbContextProvider<AiYardDbContext> dbContextProvider,
            IActiveTransactionProvider activeTransactionProvider) : base(dbContextProvider, activeTransactionProvider)
        {

        }

        #region 查询Tb_YardIssuedCard_VML

        public async Task<List<TbYardIssuedCardDb>> QueryTableIssuedCard(List<long> Station_ID, string FilterText, bool onlyShowBAccount, bool NoBAccount)
        {

            List<TbYardIssuedCardDb> tbAll = new List<TbYardIssuedCardDb>();

            string sql = "exec r_IssuedVML '" + string.Join(",", Station_ID.ToArray()) + "'" + ",N'" + FilterText + "'," + (onlyShowBAccount ? 1 : 0).ToString() + "," + (NoBAccount ? 1 : 0).ToString();
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                tbAll = DataTableExtend.ToDataList<TbYardIssuedCardDb>(dt);
            }

            return tbAll;
        }

        #endregion

        #region 查询Tb_YardIssuedCard_VMLById

        public async Task<TbYardIssuedCardDb> QueryTableIssuedCardById(long Id)
        {

            List<TbYardIssuedCardDb> tbAll = new List<TbYardIssuedCardDb>();

            string sql = " SELECT *,N'未下载' DownStatus,User_Mobile As Phone,0 As BAccount FROM [Tb_YardIssuedCard_VML] WHERE Id=" + Id + " AND  IsDeleted=0";
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                tbAll = DataTableExtend.ToDataList<TbYardIssuedCardDb>(dt);
                return tbAll[0];
            }
            return null;

        }

        #endregion

        #region 车辆管理
        #region 注销

        public async Task CardLogoutIssuedCard(TbYardIssuedCardDb tc)
        {
            var result = new Dictionary<string, string>();

            SqlParameter[] param =
            {
                new SqlParameter("@Station_ID", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@Issued_ID", System.Data.SqlDbType.BigInt), //车牌发行记录号
                new SqlParameter("@Op_Type", System.Data.SqlDbType.NVarChar, 50), //延期操作
                new SqlParameter("@Op_Account", System.Data.SqlDbType.Decimal), //金额
                new SqlParameter("@MonthCount", System.Data.SqlDbType.Int), //操作份数
                new SqlParameter("@Op_User_ID", System.Data.SqlDbType.Int), //操作员编号              
                new SqlParameter("@Op_Memo", System.Data.SqlDbType.NVarChar, 500), //车辆备注
                new SqlParameter("@New_BTime", System.Data.SqlDbType.DateTime), //起始时间
                new SqlParameter("@New_ETIme", System.Data.SqlDbType.DateTime), //结束时间           
                new SqlParameter("@TenantId", System.Data.SqlDbType.Int)

            };
            param[0].Value = tc.Station_ID;
            param[1].Value = tc.Issued_Id;
            param[2].Value = "注销";
            param[3].Value = tc.Account;
            param[4].Value = -1;
            param[5].Value = tc.OP_User_Id;
            param[6].Value = tc.Memo;
            param[7].Value = tc.BeginTime;
            param[8].Value = tc.EndTime;
            param[9].Value = tc.TenantId;

            SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "p_UpdateCardOpInfo", param);




            /*int count = 0;
            //存储过程-带参数
            using (var command =
                CreateCommand(
                    "exec p_UpdateCardOpInfo @Station_ID,@Issued_ID,@Op_Type,@Op_Account,@Op_User_ID,@Op_Memo,@New_BTime,@New_ETIme,@TenantId",
                    CommandType.Text, param))

            {
                using (var dataReader = command.ExecuteReader())
                {
                    //count = 1;
                    //while (dataReader.Read())
                    //{
                    //    result.Add("四、" + count, dataReader["Name"].ToString());
                    //    count++;
                    //}
                }
            }*/
        }

        #endregion

        #region 发卡 / 延期
        /// <summary>
        /// 发卡 / 延期
        /// </summary>
        /// <param name="tc"></param>
        /// <returns></returns>
        public async Task<Dictionary<string, string>> CreateIssuedCard(TbYardIssuedCardDb tc, int MonthCount, bool BAccount)
        {
            var result = new Dictionary<string, string>();

            SqlParameter[] param =
            {
                new SqlParameter("@Station_id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@Issued_ID", System.Data.SqlDbType.BigInt), //车牌发行记录号
                new SqlParameter("@Delay", System.Data.SqlDbType.Bit), //延期操作
                new SqlParameter("@MonthCount", System.Data.SqlDbType.Int),//操作份数
                new SqlParameter("@Card_No", System.Data.SqlDbType.NVarChar, 50), //卡号、车牌
                new SqlParameter("@PlateColor", System.Data.SqlDbType.Int), //车牌颜色
                new SqlParameter("@User_No", System.Data.SqlDbType.VarChar), //车主编号
                new SqlParameter("@User_Name", System.Data.SqlDbType.NVarChar, 50), //车主姓名
                new SqlParameter("@BeginTime", System.Data.SqlDbType.DateTime), //有效起始日期
                new SqlParameter("@EndTime", System.Data.SqlDbType.DateTime), //有效截止日期
                new SqlParameter("@Card_IOPower", System.Data.SqlDbType.VarChar), //有效机号
                new SqlParameter("@msg", System.Data.SqlDbType.NVarChar, 150),
                new SqlParameter("@CardTypeId", System.Data.SqlDbType.Int), //包月类型
                new SqlParameter("@Account", System.Data.SqlDbType.Decimal), //金额
                new SqlParameter("@OP_User_Id", System.Data.SqlDbType.Int), //操作员编号
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar, 50), //车牌
                new SqlParameter("@CarPlace", System.Data.SqlDbType.NVarChar, 500), //车位
                new SqlParameter("@User_Dept", System.Data.SqlDbType.BigInt), //车主部门
                new SqlParameter("@OP_Memo", System.Data.SqlDbType.NVarChar, 500), //车辆备注
                new SqlParameter("@CarImg", System.Data.SqlDbType.NVarChar, 500), //车辆照片
                new SqlParameter("@Phone", System.Data.SqlDbType.VarChar), //车主电话
                new SqlParameter("@RecordType", System.Data.SqlDbType.VarChar), //介质
                new SqlParameter("@Deposit", System.Data.SqlDbType.Decimal), //押金
                new SqlParameter("@CarType", System.Data.SqlDbType.NVarChar, 50), //车型 
                new SqlParameter("@CarColor", System.Data.SqlDbType.NVarChar, 50), //车辆颜色
                new SqlParameter("@IDNO", System.Data.SqlDbType.VarChar), //行驶证号
                new SqlParameter("@TenantId", System.Data.SqlDbType.Int)

            };
            param[0].Value = tc.Station_ID;
            param[1].Value = tc.Issued_Id;
            param[1].Direction = ParameterDirection.InputOutput;
            param[2].Value = tc.Delay;
            param[3].Value = MonthCount;
            param[4].Value = tc.CardNo.ToUpper();
            param[5].Value = tc.PlateColor;
            param[6].Value = tc.User_No;
            param[7].Value = tc.User_Name;
            param[8].Value = tc.BeginTime.Value.Date;
            param[9].Value = tc.EndTime.Value.Date;
            param[10].Value = tc.Card_IOPower;
            param[11].Direction = ParameterDirection.Output;
            param[12].Value = tc.CardTypeId;
            param[13].Value = tc.Account;
            param[14].Value = tc.OP_User_Id;
            param[15].Value = tc.PlateNo.ToUpper();
            param[16].Value = (string.IsNullOrEmpty(tc.CarPlace) ? "" : tc.CarPlace.Replace('，', ',').ToString());
            param[17].Value = tc.User_Dept;
            param[18].Value = tc.Memo;
            param[19].Value = tc.CarImg;
            param[20].Value = tc.Phone;
            param[21].Value = tc.RecordType;
            param[22].Value = tc.Deposit;
            param[23].Value = tc.CarType;
            param[24].Value = tc.CarColor;
            param[25].Value = tc.IDNO;
            param[26].Value = tc.TenantId;
            SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "p_UpdateIssued", param);
            if (param[11].Value.ToString().Trim() == "更新成功")
            {
                if (BAccount)
                {
                    saveHideIssuedRecord(Convert.ToInt64(param[1].Value), (long)tc.Station_ID, 1);
                }
                result.Add("retype", param[1].Value.ToString());
                result.Add("revalue", param[10].Value.ToString());
            }
            else
            {
                result.Add("retype", "-1");
                result.Add("revalue", param[11].Value.ToString());
            }
            return result;
        }
        #endregion

        #region 批量授权
        /// <summary>
        /// 批量授权
        /// </summary>
        /// <param name="Issued_ID"></param>
        /// <param name="TenantId"></param>
        /// <param name="Station_Id"></param>
        /// <param name="Card_IOPower"></param>
        /// <returns></returns>
        public int BatchAuthorizationIssuedCard(long Issued_ID, int TenantId, long Station_Id, string Card_IOPower)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            try
            {
                SqlParameter[] param =
                {
                    new SqlParameter("@Issued_ID", System.Data.SqlDbType.BigInt), //
                    new SqlParameter("@TenantId", System.Data.SqlDbType.Int), //
                    new SqlParameter("@Station_id", System.Data.SqlDbType.BigInt), //
                    new SqlParameter("@Card_IOPower", System.Data.SqlDbType.VarChar, 500)
                };
                param[0].Value = Issued_ID;
                param[1].Value = TenantId;
                param[2].Value = Station_Id;
                param[3].Value = Card_IOPower;
                SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "a_UpdateCardPower", param);

                return 1;
            }
            catch (Exception e)
            {
                return -1;
            }
        }
        #endregion

        #region 批量导入
        #region 判断是否合法车牌号码
        /// <summary>
        /// 判断是否合法车牌号码
        /// </summary>
        /// <param name="PlateNo"></param>
        /// <returns></returns>
        public static bool isPlateLicense(string PlateNo)
        {
            try
            {
                if (PlateNo == "_无_" || PlateNo == "无" || PlateNo.Contains("无"))
                {
                    return true;
                }
                string Value = "粤军警WJ港京津沪冀豫晋鲁桂滇黔川苏浙湘鄂新藏黑皖闽琼辽陕甘青吉蒙渝宁赣贵云甲乙丙丁戊己庚辛壬癸学澳港挂";
                if (PlateNo.Length < 7 || PlateNo.Length > 8)
                {
                    return false;
                }
                for (int i = 0; i < PlateNo.Length; i++)
                {
                    if (PlateNo.Substring(i, 1).ToUpper() == "I"
                        || PlateNo.Substring(i, 1).ToUpper() == "O")
                    {
                        return false;
                    }
                }
                if (!Value.Contains(PlateNo.Substring(0, 1)))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion
        public async Task<Dictionary<string, string>> BatchLoadCardNo(string fileName, long Station_ID, int TenantId, int OP_User_Id)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            result.Add("retype", "-1");
            result.Add("revalue", "导入数据成功");
            try
            {
                var errorList = new List<string>();
                string fullPath = fileName;

                IWorkbook wk = null;
                string extension = System.IO.Path.GetExtension(fullPath);

                FileStream fs = new FileStream(fullPath, FileMode.Open);
                if (extension.Equals(".xls"))
                {
                    //把xls文件中的数据写入wk中
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //把xlsx文件中的数据写入wk中
                    wk = new XSSFWorkbook(fs);
                }



                fs.Close();
                string err = "";

                //读取当前表数据
                ISheet sheet = wk.GetSheetAt(0);
                IRow row = sheet.GetRow(0);  //读取当前行数据
                string strJsonArrary = "";
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    try
                    {
                        row = sheet.GetRow(i);  //读取当前行数据
                        if (row != null && row.GetCell(0) != null && row.GetCell(0).ToString() != "" && row.GetCell(0).ToString() != "{}")
                        {

                            int CardTypeId = 1409;
                            string Name = "";
                            string Dept = "";
                            string Phone = "";
                            string CardNo = "";
                            DateTime EndTime = DateTime.Now;
                            decimal Amount = 0;
                            int PlateColor = 1;
                            string CarColor = "";
                            string IDNo = "";
                            string Power = "";

                            //LastCellNum 是当前行的总列数
                            for (int j = 1; j <= 11; j++)
                            {
                                //读取该行的第j列数据
                                if (j == 1)
                                {
                                    switch (row.GetCell(j).ToString().Trim())
                                    {
                                        case "月卡A":
                                            {
                                                CardTypeId = 1409;
                                                break;
                                            }
                                        case "月卡B":
                                            {
                                                CardTypeId = 1410;
                                                break;
                                            }
                                        case "月卡C":
                                            {
                                                CardTypeId = 1411;
                                                break;
                                            }
                                        case "月卡D":
                                            {
                                                CardTypeId = 1412;
                                                break;
                                            }
                                        case "免费卡A":
                                            {
                                                CardTypeId = 1413;
                                                break;
                                            }
                                        case "免费卡B":
                                            {
                                                CardTypeId = 1414;
                                                break;
                                            }
                                    };
                                }
                                if (j == 2)
                                {
                                    Name = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                                if (j == 3)
                                {
                                    Dept = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                                if (j == 4)
                                {
                                    Phone = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                                if (j == 5)
                                {
                                    CardNo = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                    if (CardNo == "")
                                    {
                                        CardNo = row.GetCell(j).StringCellValue.ToString().Trim();
                                    }
                                }
                                if (j == 6)
                                {
                                    string TimeStr = row.GetCell(j).ToString().Trim().Replace('/', '-');

                                    if (!DateTime.TryParse(TimeStr, out EndTime))
                                    {
                                        TimeStr = row.GetCell(j).DateCellValue.ToString();
                                        if (!DateTime.TryParse(TimeStr, out EndTime))
                                        {
                                            EndTime = new DateTime(1900, 1, 1);
                                        }
                                    }
                                }
                                if (j == 7)
                                {
                                    string AmountStr = row.GetCell(j) == null ? "0" : row.GetCell(j).ToString().Trim();

                                    if (!decimal.TryParse(AmountStr, out Amount))
                                    {
                                        AmountStr = row.GetCell(j).StringCellValue.ToString().Trim();
                                        if (!decimal.TryParse(AmountStr, out Amount))
                                        {
                                            Amount = 0;
                                        }
                                    }

                                }
                                if (j == 8)
                                {
                                    string carcolor = row.GetCell(j) == null ? "未知" : row.GetCell(j).ToString().Trim();
                                    switch (carcolor)
                                    {
                                        case "蓝色":
                                            {
                                                PlateColor = 1;
                                                break;
                                            }
                                        case "黄色":
                                            {
                                                PlateColor = 2;
                                                break;
                                            }
                                        case "白色":
                                            {
                                                PlateColor = 3;
                                                break;
                                            }
                                        case "黑色":
                                            {
                                                PlateColor = 4;
                                                break;
                                            }
                                        case "绿色":
                                            {
                                                PlateColor = 5;
                                                break;
                                            }
                                        case "未知":
                                            {
                                                PlateColor = 6;
                                                break;
                                            }
                                    };
                                }
                                if (j == 9)
                                {
                                    CarColor = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                                if (j == 10)
                                {
                                    IDNo = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                                if (j == 11)
                                {
                                    Power = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                }
                            }
                            if (Name == "" || CardNo == "")
                            {
                                err = err + i.ToString() + "(名称或车牌为空),";
                            }
                            else if (!isPlateLicense(CardNo))
                            {
                                err = err + i.ToString() + "(车牌不合法),";
                            }
                            else if (EndTime == new DateTime(1900, 1, 1))
                            {
                                err = err + i.ToString() + "(日期错误),";
                            }
                            else if (Power == "")
                            {
                                err = err + i.ToString() + "(权限为空),";
                            }
                            else
                            {
                                string IOPower = GetIOPowerList(Station_ID, Power);
                                if (IOPower == "")
                                {
                                    err = err + i.ToString() + "(权限为空),";
                                }
                                else
                                {
                                    TbYardIssuedCardDb tc = new TbYardIssuedCardDb();
                                    tc.Station_ID = Station_ID;
                                    tc.Issued_Id = 0;
                                    tc.Delay = false;
                                    tc.CardNo = CardNo;
                                    tc.PlateColor = PlateColor;
                                    tc.User_No = "";
                                    tc.User_Name = Name;
                                    tc.BeginTime = DateTime.Now.Date;
                                    tc.EndTime = EndTime.Date;
                                    tc.Card_IOPower = IOPower;
                                    tc.CardTypeId = CardTypeId;
                                    tc.Account = Amount;
                                    tc.OP_User_Id = OP_User_Id;
                                    tc.PlateNo = CardNo;
                                    tc.CarPlace = "";
                                    tc.User_Dept = 0;
                                    tc.Memo = "";
                                    tc.CarImg = "";
                                    tc.Phone = Phone;
                                    tc.RecordType = "CP";
                                    tc.Deposit = 0;
                                    tc.CarType = "";
                                    tc.CarColor = CarColor;
                                    tc.IDNO = IDNo;
                                    tc.TenantId = TenantId;
                                    int MonthCard = -1;
                                    Dictionary<string, string> result2 = await CreateIssuedCard(tc, MonthCard, false);
                                    string value = "";
                                    if (result2.TryGetValue("retype", out value))
                                    {
                                        if (value == "-1")
                                        {
                                            err = err + i.ToString() + ",";
                                        }
                                        else
                                        {

                                            long issuedId = long.Parse(value);
                                            AddIssuedCardPay(Station_ID, issuedId, 0, EndTime.Date, "发行", Amount, 0, 0, "现金");
                                        }
                                    }
                                    else
                                    {
                                        err = err + i.ToString() + ",";
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exx)
                    {
                        LogHelper.Logger.Error(exx.Message);
                        err = err + i.ToString() + ",";
                    }
                }
                if (err != "")
                {
                    result.Clear();
                    result.Add("retype", "-1");
                    result.Add("revalue", "错误的行【" + err + "】");
                }
            }
            catch (Exception e)
            {
                result.Clear();
                result.Add("retype", "-1");
                result.Add("revalue", e.Message);
            }
            return result;
        }

        public string GetIOPowerList(long Station_ID, string IOPower)
        {
            try
            {
                string strSql = "select b.Id from [dbo].[f_GetStrArray]('" + IOPower + "',',') a left join (SELECT TDev_No devid, ID FROM Tb_YardDevice A WHERE  "
                    + " A.Station_ID=" + Station_ID + " AND A.IsDeleted=0) b on CONVERT(bigint,substr)=b.devid";
                DataTable db = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (db != null && db.Rows.Count > 0)
                {
                    string P = "";
                    foreach (DataRow row in db.Rows)
                    {
                        P = P + row["Id"].ToString() + ",";
                    }
                    return P.Trim(',');
                }
                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        #endregion

        #region 获取月卡延期规则
        public async Task<List<TbYardMonthCardOnline>> GetTbYardMonthCardOnlines(long Station_ID)
        {
            List<TbYardMonthCardOnline> cardOnlines = new List<TbYardMonthCardOnline>();
            try
            {

                string sql = string.Format(
                "select * from [Tb_YardMonthCardOnline] where IsDeleted=0 and [Station_ID]={0}",
                Station_ID);
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    cardOnlines = DataTableExtend.ToDataList<TbYardMonthCardOnline>(dt);
                }
                return cardOnlines;
            }
            catch (Exception ex)
            {
                return cardOnlines;
            }
        }
        #endregion

        #region 按包月规则计算
        public async Task<TbYardIssuedMonthOnlineResult> CaleMonthCardOnlines(long IssuedId, long Station_Id, int CardTypeId, int MonthCount)
        {

            try
            {
                SqlParameter[] param =
                {
                new SqlParameter("@Issued_Id", System.Data.SqlDbType.BigInt), //发行编号 
                new SqlParameter("@CardTypeId", System.Data.SqlDbType.Int), //卡类
                new SqlParameter("@StationId", System.Data.SqlDbType.BigInt, 50), //车场 
                new SqlParameter("@MonthCount", System.Data.SqlDbType.Int),//操作份数

                new SqlParameter("@oLdEndTime", System.Data.SqlDbType.DateTime), //旧截至日期
                new SqlParameter("@nEwEndTime", System.Data.SqlDbType.DateTime), //新截止日期
                new SqlParameter("@PurMoney", System.Data.SqlDbType.Decimal), //金额
                new SqlParameter("@PayMoney", System.Data.SqlDbType.Decimal), //应支付
                new SqlParameter("@YHMoney", System.Data.SqlDbType.Decimal), //优惠
                new SqlParameter("@OpTypeInfor", System.Data.SqlDbType.NVarChar, 50), //操作方式
                new SqlParameter("@Error", System.Data.SqlDbType.NVarChar, 50), //错误
            };
                param[0].Value = IssuedId;
                param[1].Value = CardTypeId;
                param[2].Value = Station_Id;
                param[3].Value = MonthCount;
                param[4].Direction = ParameterDirection.Output;
                param[5].Direction = ParameterDirection.Output;
                param[6].Direction = ParameterDirection.Output;
                param[7].Direction = ParameterDirection.Output;
                param[8].Direction = ParameterDirection.Output;
                param[9].Direction = ParameterDirection.Output;
                param[10].Direction = ParameterDirection.Output;

                DataSet db = SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "O_CaleMonthOnline", param);
                if (db != null && db.Tables.Count > 0)
                {
                    TbYardIssuedMonthOnlineResult result = new TbYardIssuedMonthOnlineResult();
                    result.monthType = int.Parse(db.Tables[0].Rows[0]["MonthType"].ToString());
                    result.oldEndTime = Convert.ToDateTime(db.Tables[0].Rows[0]["oldEndTime"]);
                    result.newEndTime = Convert.ToDateTime(db.Tables[0].Rows[0]["newEndTime"]);
                    result.purMoney = Convert.ToDecimal(db.Tables[0].Rows[0]["PurMoney"]);
                    result.payMoney = Convert.ToDecimal(db.Tables[0].Rows[0]["PayMoney"]);
                    result.yhMoney = Convert.ToDecimal(db.Tables[0].Rows[0]["YHMoney"]);
                    return result;

                }
            }
            catch { }
            TbYardIssuedMonthOnlineResult result2 = new TbYardIssuedMonthOnlineResult();
            result2.monthType = 2;
            result2.oldEndTime = DateTime.Now.Date;
            result2.newEndTime = DateTime.Now.Date.AddMonths(MonthCount);
            result2.purMoney = 0;
            result2.payMoney = 0;
            result2.yhMoney = 0;
            return result2;
        }
        #endregion

        #region 更新支付状态
        public async Task<bool> AddIssuedCardPay(long Station_Id, long IssuedId, long IssuedOpId,
            DateTime EndTime, string OpType, decimal PurMoney, decimal PayMoney, decimal YHMoney, string PayType)
        {

            try
            {
                SqlParameter[] param =
                {
                new SqlParameter("@StationId",SqlDbType.BigInt),
                new SqlParameter("@IssuedId",SqlDbType.BigInt),
                new SqlParameter("@IssuedOpId",SqlDbType.BigInt),
                new SqlParameter("@EndTime",SqlDbType.DateTime),
                new SqlParameter("@Status",SqlDbType.NVarChar,50),
                new SqlParameter("@OpType",SqlDbType.NVarChar,50),
                new SqlParameter("@ResultId",SqlDbType.BigInt),
                new SqlParameter("@PurMoney",SqlDbType.Decimal),
                new SqlParameter("@PayMoney",SqlDbType.Decimal),
                new SqlParameter("@YHMoney",SqlDbType.Decimal),
                new SqlParameter("@OpenId",SqlDbType.VarChar,50),
                new SqlParameter("@PayTime",SqlDbType.DateTime),
                new SqlParameter("@PayType",SqlDbType.NVarChar,50),
            };
                param[0].Value = Station_Id;
                param[1].Value = IssuedId;
                param[2].Value = 0;
                param[3].Value = EndTime;
                param[4].Value = "支付成功";
                param[5].Value = OpType;
                param[6].Value = 0;
                param[7].Value = PurMoney;
                param[8].Value = PayMoney;
                param[9].Value = YHMoney;
                param[10].Value = "";
                param[11].Value = DateTime.Now;
                param[12].Value = PayType;

                return SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "O_AddIssuedCardPay", param) > 0;
            }
            catch { }
            return false;
        }
        #endregion

        #region 删除下载标识
        public async Task<bool> DeleteDownTag(long Station_Id, string IdList)
        {
            try
            {
                string strSql = "DECLARE @Station_No nvarchar(20) SELECT  @Station_No=Station_No FROM tB_Station WHERE Station_Id=" + Station_Id
                    + " exec('DELETE FROM [tY_DataDownResult_'+@Station_No+'] WHERE ID IN (SELECT ID FROM tB_YardIssuedCardPower WHERE Station_ID=" + Station_Id
                    + " AND Issued_ID IN (SELECT ID FROM Tb_YardIssuedCard WHERE Station_ID=" + Station_Id + " AND Id IN (" + IdList + "))) AND [TableName]=''tB_YardIssuedCardPower'' "
                    + " DELETE FROM tY_DataDownResult_'+@Station_No+' WHERE [ID] IN (" + IdList + ") AND [TableName]=''tB_YardIssuedCard'' ')";
                SqlHelper.ExecuteNonQuery(GetCon(), CommandType.Text, strSql);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion
        #endregion

        #region 获取设备号

        public string GetCard_IOPower(long Issued_ID)
        {
            try
            {
                string Card_IOPower = "";

                string sql = string.Format("select * from [dbo].[tB_YardIssuedCardPower] where [Issued_ID]={0}",
                    Issued_ID);
                using (var command1 = CreateCommand(sql, CommandType.Text))
                {
                    using (var dataReader1 = command1.ExecuteReader())
                    {
                        while (dataReader1.Read())
                        {
                            Card_IOPower += dataReader1["Dev_ID"].ToString().Trim() + ",";
                        }
                    }
                }

                if (!string.IsNullOrEmpty(Card_IOPower))
                    Card_IOPower = Card_IOPower.TrimEnd(',');
                return Card_IOPower;
            }
            catch (Exception ex)
            {
                return "";
            }

            //throw new NotImplementedException();
        }

        #endregion

        #region 获取车位

        public string GetParkingPos(long User_ID, long StationId)
        {
            try
            {
                string ParkingPos = "";

                string strSql = string.Format("select * from [dbo].[Tb_YardUserParking_ParkingPos_VML] where [User_ID]={0} AND [Station_Id]=" + StationId + " ", User_ID);
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count >= 1)
                {
                    ParkingPos = dt.Rows[0]["ParkingPos"].ToString().Trim();
                }
                //using (var command = CreateCommand(sql, CommandType.Text))
                //{
                //    using (var dataReader = command.ExecuteReader())
                //    {
                //        ParkingPos = dataReader["ParkingPos"].ToString().Trim();
                //        //while (dataReader.Read())
                //        //{
                //        //    ParkingPos += dataReader["ParkingPos"].ToString().Trim() + ",";
                //        //}
                //    }
                //}

                if (!string.IsNullOrEmpty(ParkingPos))
                    ParkingPos = ParkingPos.TrimEnd(',');
                return ParkingPos;
            }
            catch
            {
                return "";
            }
        }

        #endregion

        #region 获取图片FileId
        public bool GetImagesFileId2(int IN_OUT, long RecordId, long StationId, ref string StationNo, ref string InImages, ref string OutImages)
        {
            try
            {
                string strSql = "";
                if (IN_OUT == 1)
                {
                    strSql = $@"declare @StationNo varchar(20) 
                                select @StationNo = Station_No from Tb_Station where Station_ID = {StationId}
                                exec('SELECT top 1 '''+@StationNo+''''+' as StationNo,  tIN_Image1,'''' tOut_Image1 FROM tY_InYard_' + @StationNo + ' where tIN_ID={RecordId}') ";
                }
                else if (IN_OUT == 2)
                {
                    strSql = $@"declare @StationNo varchar(20) 
                                select @StationNo = Station_No from Tb_Station where Station_ID = {StationId}
                                exec('SELECT  top 1 '''+@StationNo+''''+' as StationNo, tIN_Image1,tOut_Image1 FROM tY_OutYard_' + @StationNo + ' where tOut_Id={RecordId}') ";
                }
                else
                {
                    strSql = $@"declare @StationNo varchar(20) 
                                select @StationNo = Station_No from Tb_Station where Station_ID = {StationId}
                                exec('SELECT  top 1 '''+@StationNo+''''+' as StationNo, tImage1 tIN_Image1,'''' tOut_Image1 FROM tY_OpenGate_' + @StationNo + ' where tOpen_ID={RecordId}') ";
                }

                DataSet db = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql);
                StationNo = "";
                InImages = "";
                OutImages = "";
                if (db != null && db.Tables != null && db.Tables[0].Rows.Count > 0)
                {
                    string result = "";
                    foreach (DataRow row in db.Tables[0].Rows)
                    {
                        StationNo = row["StationNo"].ToString();

                        if (row["tIN_Image1"].ToString() != "")
                        {
                            InImages = row["tIN_Image1"].ToString();
                        }
                        if (row["tOut_Image1"].ToString() != "")
                        {
                            OutImages = row["tOut_Image1"].ToString();
                        }
                    }
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        public List<string> GetImagesFileId(int IN_OUT, long RecordId, long StationId)
        {
            try
            {

                string strSql = "declare @StationNo varchar(20) "
                              + " select @StationNo = Station_No from Tb_Station where Station_ID = " + StationId + " "
                              + " if " + IN_OUT + " = 1 or " + IN_OUT + " = 3"
                              + " begin "
                              + " exec( "
                              + " 'SELECT [IN_OUT],[foldersNo],[fileName],[ImageName],[StationNo] FROM [dbo].[tY_Images_' + @StationNo + '] WHERE [IN_OUT]=" + IN_OUT + " and [RecordId]=" + RecordId + " ' "
                              + " ) "
                              + " end "
                              + " else "
                              + " begin "
                              + " exec( "
                              + " 'SELECT * FROM (SELECT [IN_OUT],[foldersNo],[fileName],[ImageName],[StationNo] FROM [dbo].[tY_Images_' + @StationNo + '] WHERE [IN_OUT]=" + IN_OUT + " and [RecordId]=" + RecordId + "  "
                              + "  union all "
                              + "  SELECT [IN_OUT],[foldersNo],[fileName],[ImageName],[StationNo] FROM [dbo].[tY_Images_'+@StationNo+'] WHERE [IN_OUT] = 1 and [RecordId] = (select tIN_ID from [dbo].[tY_OutYard_'+@StationNo+'] where tOut_Id = " + RecordId + ")) TA ORDER BY IN_OUT ' "
                              + " ) "
                              + " end";
                DataSet db = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql);
                if (db != null && db.Tables != null && db.Tables[0].Rows.Count > 0)
                {
                    List<string> result = new List<string>();
                    foreach (DataRow row in db.Tables[0].Rows)
                    {
                        string[] filename = row["ImageName"].ToString().Split('\\');

                        result.Add(row["StationNo"].ToString() + "$" + row["foldersNo"].ToString() + "$" + row["fileName"].ToString() + "$" + filename[filename.Length - 1]);
                    }
                    return result;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region 获取电话 

        public Dictionary<string, string> GetPhone(long User_ID)
        {
            try
            {
                //string[] strPhone;

                var strPhone = new Dictionary<string, string>();

                string sql = string.Format("select * from [dbo].[Tb_User] where [ID]={0}", User_ID);
                using (var command = CreateCommand(sql, CommandType.Text))
                {
                    using (var dataReader = command.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            //strPhone. = dataReader["User_Mobile"].ToString().Trim();
                            strPhone.Add("User_Mobile", dataReader["User_Mobile"].ToString().Trim());
                            strPhone.Add("User_No", dataReader["User_No"].ToString().Trim());
                            strPhone.Add("User_Name", dataReader["User_Name"].ToString().Trim());
                            strPhone.Add("User_Dept", dataReader["User_Dept"].ToString().Trim());
                        }
                    }
                }

                return strPhone;
            }
            catch
            {
                return new Dictionary<string, string>();
            }
        }

        #endregion

        #region 测试用

        public async Task TestTable()
        {
            //throw new NotImplementedException();
            var result = new Dictionary<string, string>();
            SqlParameter[] param =
            {
                new SqlParameter("@TName", System.Data.SqlDbType.VarChar),
                new SqlParameter("@Msg", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@TKD", System.Data.SqlDbType.BigInt),
                new SqlParameter("@K10", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K11", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K12", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K13", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K14", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K15", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K16", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K17", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K18", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K19", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K20", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K21", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K22", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K23", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K24", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K25", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K26", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K27", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K28", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K29", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K30", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K31", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K32", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K33", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@K34", System.Data.SqlDbType.NVarChar, 50),
                new SqlParameter("@KKD", System.Data.SqlDbType.Bit),
                new SqlParameter("@BeginTime", System.Data.SqlDbType.DateTime)

            };

            param[0].Value = "123213";
            param[1].Direction = ParameterDirection.Output;
            param[2].Value = 12;
            param[3].Value = "10";
            param[4].Value = "11";
            param[5].Value = "12";
            param[6].Value = "13";
            param[7].Value = "14";
            param[8].Value = "15";
            param[9].Value = "16";
            param[10].Value = "17";
            param[11].Value = "18";
            param[12].Value = "19";
            param[13].Value = "20";
            param[14].Value = "21";
            param[15].Value = "22";
            param[16].Value = "23";
            param[17].Value = "24";
            param[18].Value = "25";
            param[19].Value = "26";
            param[20].Value = "27";
            param[21].Value = "28";
            param[22].Value = "29";
            param[23].Value = "30";
            param[24].Value = "31";
            param[25].Value = "32";
            param[26].Value = "33";
            param[27].Value = "34";
            param[28].Value = false;
            param[29].Value = DateTime.Now;




            int count = 0;
            //存储过程-带参数
            using (var command =
                CreateCommand(
                    "exec CrTest @TName,@Msg output,@TKD,@K10,@K11,@K12,@K13,@K14,@K15,@K16,@K17,@K18,@K19,@K20,@K21,@K22,@K23,@K24,@K25,@K26,@K27,@K28,@K29,@K30,@K31,@K32,@K33,@K34,@KKD,@BeginTime",
                    CommandType.Text, param))
            {
                using (var dataReader = command.ExecuteReader())
                {
                    count = 1;
                    while (dataReader.Read())
                    {
                        result.Add("四、" + count, dataReader["Name"].ToString());
                        count++;
                    }
                }
            }

        }

        #endregion

        #region 获取用户

        public List<TbrYardUserDto> GetUserList(long Station_ID, string QueryUserName)
        {
            try
            {
                var strAllUser = new List<TbrYardUserDto>();
                string sql = string.Format("select a.Id,isnull(b.Id,0) as deptId,a.user_name,a.User_No,isnull(b.Depart_Name,N'') Depart_Name from [dbo].[Tb_User] A left join [dbo].[Tb_Depart] B ON a.[User_Dept]=b.[Id] where A.IsDeleted=0 and A.Station_ID={0} " +
                    " and a.user_Name like N'%{1}%'", Station_ID, QueryUserName);
                using (var command = CreateCommand(sql, CommandType.Text))
                {
                    using (var dataReader = command.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            var strUser = new TbrYardUserDto();
                            strUser.Id = long.Parse(dataReader["Id"].ToString());
                            strUser.username = dataReader["user_name"].ToString().Trim();
                            strUser.userno = dataReader["User_No"].ToString().Trim();
                            strUser.deptname = dataReader["Depart_Name"].ToString().Trim();
                            strUser.deptId = long.Parse(dataReader["deptId"].ToString());
                            //strUser.Add("id", dataReader["Id"].ToString().Trim());
                            //strUser.Add("user_name", dataReader["user_name"].ToString().Trim());
                            strAllUser.Add(strUser);
                        }
                    }
                }

                return strAllUser;
            }
            catch (Exception ex)
            {
                return new List<TbrYardUserDto>();
            }
        }

        #endregion

        #region 测试获取用户

        public Dictionary<string, string> gettestUser(long Station_ID)
        {
            var result = new Dictionary<string, string>();
            string con = Context.Database.GetDbConnection().ConnectionString;
            SqlParameter[] param =
            {
                new SqlParameter("@strName", System.Data.SqlDbType.NVarChar,50),
                new SqlParameter("@TestName", System.Data.SqlDbType.VarChar),
                new SqlParameter("@KID", System.Data.SqlDbType.Int),
                new SqlParameter("@ID", System.Data.SqlDbType.Int),
                new SqlParameter("@Msg", System.Data.SqlDbType.NVarChar, 50)

            };

            param[0].Value = "strName";
            param[1].Value = "TestName";
            param[2].Value = 12;
            param[3].Direction = ParameterDirection.Output;
            param[4].Direction = ParameterDirection.Output;

            SqlHelper.ExecuteNonQuery(con, CommandType.StoredProcedure, "TestSML", param);
            result.Add(param[3].Value.ToString(), param[4].Value.ToString());
            return result;
        }

        #endregion

        #region Con字符串
        /// <summary>
        /// Con字符串
        /// </summary>
        /// <returns></returns>
        private string GetCon()
        {
            return Context.Database.GetDbConnection().ConnectionString;
        }
        #endregion

        #region 查询设备参数设置
        /// <summary>
        /// 查询设备参数设置
        /// </summary>
        /// <param name="Station_ID">组织ID</param>
        /// <returns></returns>
        public async Task<List<TbYardParamsSetDb>> QueryTableYardParamsSet(List<long> Station_ID)
        {
            string strSql = string.Format("SELECT * FROM Tb_YardParamsSet_VML WHERE Station_ID in ({0})", string.Join(",", Station_ID.ToArray()));
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                List<TbYardParamsSetDb> YardPs = DataTableExtend.ToDataList<TbYardParamsSetDb>(dt);
                return YardPs;
            }
            else
                return new List<TbYardParamsSetDb>();
        }
        #endregion

        #region 车场参数List
        /// <summary>
        /// 车场参数List
        /// </summary>
        /// <param name="Station_ID">组织ID</param>
        /// <returns></returns>
        public List<TbStationParam> GetTbStationParamTable(long Station_ID)
        {
            List<TbStationParam> spAll = new List<TbStationParam>();
            string strSql = string.Format("Select * from dbo.Tb_StationParams Where Station_ID={0} AND SYGJ=1", Station_ID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbStationParam>(dt);
            }
            return spAll;
        }
        #endregion

        #region 获取临时密码
        public string GetTbStationParamTablePassword()
        {
            try
            {
                string strSql = "Select * from dbo.Tb_StationParams Where Station_ID=-1 AND Client_ID=-1 AND SYGJ=1  AND [SYIP]='127.0.0.1' AND [SYNM]='TempPasswordToRegDevs'";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    return dt.Rows[0]["SYVL"].ToString();
                }
                return "";
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 开启B账功能
        public bool OpenBAccount(string StationNo)
        {
            try
            {
                string strSql = "EXEC [O_YardCreateTableSyc] '" + StationNo + "'";
                return SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) > 0;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 保存车场数据
        /// <summary>
        /// 保存车场数据
        /// </summary>
        /// <param name="input">List<TbStationParam>数据</param>
        /// <returns></returns>
        public Dictionary<string, string> UpdateStationParams(List<TbStationParam> input)
        {
            var result = new Dictionary<string, string>();
            try
            {
                string strUpdate = "";
                foreach (TbStationParam tp in input)
                {
                    strUpdate += string.Format("UPDATE dbo.Tb_StationParams SET SYVL='{3}' WHERE Station_ID={0} AND SYGJ=1 AND SYID={1} AND SYNM='{2}'    ", tp.Station_ID, tp.SYID, tp.SYNM, tp.SYVL);
                }
                //统一更新
                if (SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strUpdate) > 0)
                {
                    result.Add("retype", "1");
                    result.Add("revalue", "");
                }
                else
                {
                    result.Add("retype", "-1");
                    result.Add("revalue", "保存车场内容失败");
                }

            }
            catch (Exception ex)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "发生错误！");
            }
            return result;
        }
        #endregion

        #region 初始化车场参数 
        public void InitYardParams(long Station_Id)
        {
            try
            {
                string strSql = "DELETE FROM [tB_StationParams] WHERE [STATION_ID]=" + Station_Id.ToString() + "  ";
                SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql);
                return;

            }
            catch (Exception ex)
            {
                return;
            }
        }
        /// <summary>
        /// 初始化车场参数
        /// </summary>
        /// <param name="Station_Id"></param>
        /// <param name="Client_Id"></param>
        /// <param name="synm"></param>
        /// <param name="syip"></param>
        /// <param name="syds"></param>
        /// <param name="syty"></param>
        /// <param name="syvl"></param>
        /// <param name="sygj"></param>
        /// <returns></returns>
        public void InitYardParams(long Station_Id, long Client_Id, string synm, string syip, string syds, string syty, string syvl, bool sygj)
        {
            try
            {
                string strSql = " ";
                string strInsert = "";

                if (sygj)
                {
                    strSql = "SELECT [SYVL] FROM [tB_StationParams] WHERE [STATION_ID]=" + Station_Id.ToString() + " AND [CLIENT_ID]=0 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1 ";

                    strInsert = " DELETE FROM [tB_StationParams] WHERE [STATION_ID]=" + Station_Id.ToString() + " AND [CLIENT_ID]=0 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1 "
                              + " INSERT [tB_StationParams]([STATION_ID],[CLIENT_ID],[SYIP],[SYNM],[SYDS],[SYTY],[SYVL],[SYGJ],[SYDT]) VALUES "
                              + " (@STATION_ID,@CLIENT_ID,@SYIP,@SYNM,@SYDS,@SYTY,@SYVL,@SYGJ,@SYDT)";
                }
                else
                {
                    strSql = "SELECT [SYVL] FROM [tB_StationParams] WHERE [STATION_ID]=" + Station_Id.ToString() + " AND [CLIENT_ID]=" + Client_Id + " AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=0 ";

                    strInsert = " DELETE FROM [tB_StationParams] WHERE [STATION_ID]=" + Station_Id.ToString() + " AND [CLIENT_ID]=" + Client_Id + " AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=0 "
                              + " INSERT [tB_StationParams]([STATION_ID],[CLIENT_ID],[SYIP],[SYNM],[SYDS],[SYTY],[SYVL],[SYGJ],[SYDT]) VALUES "
                              + " (@STATION_ID,@CLIENT_ID,@SYIP,@SYNM,@SYDS,@SYTY,@SYVL,@SYGJ,@SYDT)";
                }
                if (Station_Id == -1 && Client_Id == -1)
                {
#if DEBUG
                    strInsert = " IF NOT EXISTS(SELECT [SYVL] FROM [tB_StationParams] WHERE [STATION_ID]=-1 AND [CLIENT_ID]=-1 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1 AND SYDT>=DATEADD(SECOND,-30,GETDATE())) BEGIN "
                                 + " DELETE FROM [tB_StationParams] WHERE [STATION_ID]=-1 AND [CLIENT_ID]=-1 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1"
                                 + " INSERT [tB_StationParams]([STATION_ID],[CLIENT_ID],[SYIP],[SYNM],[SYDS],[SYTY],[SYVL],[SYGJ],[SYDT]) VALUES "
                                 + " (@STATION_ID,@CLIENT_ID,@SYIP,@SYNM,@SYDS,@SYTY,@SYVL,@SYGJ,@SYDT) END ";
#else
                    strInsert = " IF NOT EXISTS(SELECT [SYVL] FROM [tB_StationParams] WHERE [STATION_ID]=-1 AND [CLIENT_ID]=-1 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1 AND SYDT>=DATEADD(MINUTE,-30,GETDATE())) BEGIN "
                                 + " DELETE FROM [tB_StationParams] WHERE [STATION_ID]=-1 AND [CLIENT_ID]=-1 AND [SYIP]='127.0.0.1' AND [SYNM]='" + synm + "' AND [SYGJ]=1"
                                 + " INSERT [tB_StationParams]([STATION_ID],[CLIENT_ID],[SYIP],[SYNM],[SYDS],[SYTY],[SYVL],[SYGJ],[SYDT]) VALUES "
                                 + " (@STATION_ID,@CLIENT_ID,@SYIP,@SYNM,@SYDS,@SYTY,@SYVL,@SYGJ,@SYDT) END ";
#endif
                    SqlParameter[] param = {
                         new SqlParameter("@STATION_ID",SqlDbType.BigInt),
                         new SqlParameter("@CLIENT_ID",SqlDbType.BigInt),
                         new SqlParameter("@SYIP",SqlDbType.VarChar,50),
                         new SqlParameter("@SYNM",SqlDbType.VarChar,40),
                         new SqlParameter("@SYDS",SqlDbType.NVarChar,50),
                         new SqlParameter("@SYTY",SqlDbType.VarChar,20),
                         new SqlParameter("@SYVL",SqlDbType.VarChar,255),
                         new SqlParameter("@SYGJ",SqlDbType.Bit),
                         new SqlParameter("@SYDT",SqlDbType.DateTime),
                    };
                    param[0].Value = Station_Id;
                    param[1].Value = Client_Id;
                    param[2].Value = "127.0.0.1";
                    param[3].Value = synm;
                    param[4].Value = syds;
                    param[5].Value = syty;
                    param[6].Value = syvl;
                    param[7].Value = sygj;
                    param[8].Value = DateTime.Now;
                    SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strInsert, param);
                }
                else
                {
                    DataTable db = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                    if (db == null || db.Rows.Count <= 0)
                    {

                        //默认值由新建车场时增加
                        try
                        {
                            SqlParameter[] param = {
                         new SqlParameter("@STATION_ID",SqlDbType.BigInt),
                         new SqlParameter("@CLIENT_ID",SqlDbType.BigInt),
                         new SqlParameter("@SYIP",SqlDbType.VarChar,50),
                         new SqlParameter("@SYNM",SqlDbType.VarChar,40),
                         new SqlParameter("@SYDS",SqlDbType.NVarChar,50),
                         new SqlParameter("@SYTY",SqlDbType.VarChar,20),
                         new SqlParameter("@SYVL",SqlDbType.VarChar,255),
                         new SqlParameter("@SYGJ",SqlDbType.Bit),
                         new SqlParameter("@SYDT",SqlDbType.DateTime),
                        };
                            param[0].Value = Station_Id;
                            param[1].Value = (sygj ? 0 : Client_Id);
                            param[2].Value = "127.0.0.1";
                            param[3].Value = synm;
                            param[4].Value = syds;
                            param[5].Value = syty;
                            param[6].Value = syvl;
                            param[7].Value = sygj;
                            param[8].Value = DateTime.Now;
                            SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strInsert, param);
                        }
                        catch (Exception ee)
                        {

                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// 获取场所参数
        /// </summary>
        /// <param name="Station_Id">场所编号</param>
        /// <param name="Client_Id">客户端编号</param> 
        /// <returns></returns>
        public void InitYardParams(long Station_Id, long Client_Id)
        {
            try
            {
                if (Client_Id == -999)
                {
                    InitYardParams(Station_Id);
                }
                /// <summary>
                /// 收费方式 24小时 分段收 月卡分时收等
                /// </summary> 
                InitYardParams(Station_Id, Client_Id, "PayModel", "", "收费方式", "STRING", "24小时", true);
                /// <summary>
                /// 超时收费模式
                /// </summary> 
                InitYardParams(Station_Id, Client_Id, "OverTimePayModel", "", "超时收费模式", "STRING", "按金额", true);
                /// <summary>
                /// 满位月卡允进
                /// </summary> 
                InitYardParams(Station_Id, Client_Id, "Full_Month_In", "", "满位月卡允进", "BOOL", "false", true);
                /// <summary>
                /// 满位固定车位车允进
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "Full_Fixed_In", "", "满位固定车位车允进", "BOOL", "false", true);
                /// <summary>
                /// 多位多车停满确认放行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "More_Fixed_In", "", "多位多车停满确认放行", "BOOL", "false", true);
                /// <summary>
                /// 满位VIP车辆允进
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "Full_Vip_In", "", "满位VIP车辆允进", "BOOL", "false", true);
                /// <summary>
                /// 满位特权车允进
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "Full_Privilege_In", "", "满位特权车允进", "BOOL", "true", true);
                /// <summary>
                /// 满位临时车允进
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "Full_Guest_In", "", "满位临时车允进", "BOOL", "false", true);
                /// <summary>
                /// 启用网络免单券
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "UseNetFreeBill", "", "启用网络免单券", "BOOL", "false", true);
                /// <summary>
                /// 启用扫码进出
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iScanBarCodeINOUTPAY", "", "启用扫码进出", "BOOL", "false", true);
                /// <summary>
                /// 启用小票进出
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iScanPrintTicket", "", "启用小票进出", "BOOL", "false", true);
                /// <summary>
                /// 启用扫显示屏二维码付费
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iScanBarCodePay", "", "启用扫显示屏二维码付费", "BOOL", "false", true);
                /// <summary>
                /// 启用客户端无感支付
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iCCBWGPay", "", "启用客户端无感支付", "BOOL", "false", true);
                /// <summary>
                /// 客户端不显示统计
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iNoShowStaticsMoney", "", "客户端不显示统计", "BOOL", "false", true);
                /// <summary>
                /// 停车时间不显示不播报
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iNoShowStopTimeSecond", "", "停车时间不显示不播报", "BOOL", "false", true);
                /// <summary>
                /// 收费金额不显示不播报
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iNoShowPaymentAmount", "", "收费金额不显示不播报", "BOOL", "false", true);
                /// <summary>
                /// 包月车不播报语音
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iNoShowVoiceMonthCard", "", "包月车不播报语音", "BOOL", "false", true);
                /// <summary>
                /// 过期车辆不允许进入小车场
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "isOverTimeCanInSamllYard", "", "过期车辆不允许进入小车场", "BOOL", "false", true);
                /// <summary>
                /// 启用小桔充电优惠
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iXiaoJuStopTimePay", "", "启用小桔充电优惠", "BOOL", "false", true);
                /// <summary>
                /// 启用多位多车功能
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iMorePlaceMoreCar", "", "启用多位多车功能", "BOOL", "false", true);
                /// <summary>
                /// 多位多车车辆绑定延期
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "MorePlaceMoreCarBindYQ", "", "多位多车车辆绑定延期", "BOOL", "false", true);
                /// <summary>
                /// 监控界面隐藏异常金额
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "MonitorNotShowExceptAmt", "", "监控界面隐藏异常金额", "BOOL", "true", true);
                /// <summary>
                /// 黄牌车默认临时卡B
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "YellowPlateToTemp2", "", "黄牌车默认临时卡B", "BOOL", "false", true);
                /// <summary>
                /// VIP车辆提示剩余天数
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "VIPShowDay", "", "VIP车辆提示剩余天数", "BOOL", "false", true);
                /// <summary>
                /// 一进一出控制
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "OneINOneOut", "", "一进一出控制", "BOOL", "false", true);
                /// <summary>
                /// 入口屏显示车位数
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayShowParkCount", "", "入口屏显示车位数", "BOOL", "true", true);
                /// <summary>
                /// 入口屏仅做车位显示屏
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "INDisplayOnlyShowParkCount", "", "入口屏仅做车位显示屏", "BOOL", "false", true);
                /// <summary>
                /// 显示屏通过透传方式发送
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayShowByVedio485", "", "显示屏通过透传方式发送", "BOOL", "true", true);
                /// <summary>
                /// 图片暂存路径
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "ImageSavePath", "", "图片暂存路径", "STRING", @"D:\PIC\", true);
                /// <summary>
                /// 图片暂存天数
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "ImageSaveDay", "", "图片暂存天数", "INT", "30", true);
                /// <summary>
                /// 出口确认开闸框点取消-返回场内
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "CancelOut", "", "出口确认开闸框点取消-返回场内", "BOOL", "false", true);
                /// <summary>
                /// 入口确认开闸框点取消-放弃入场
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "CancelIN", "", "入口确认开闸框点取消-放弃入场", "BOOL", "false", true);
                /// <summary>
                /// 允许错误位数 0,1,2,3
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "MatchingNum", "", "允许错误位数 0,1,2,3", "INT", "0", true);
                /// <summary>
                /// 同通道检查间隔时间
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "SamePassCheckInterval", "", "同通道检查间隔时间", "BOOL", "true", true);
                /// <summary>
                /// 判断进出&识别间隔时间
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "IOProcedureSecond", "", "判断进出&识别间隔时间", "INT", "5", true);
                /// <summary>
                /// 暂时关闭获取路政支付
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "TempCloseRoadUpData", "", "暂时关闭获取路政支付", "BOOL", "false", true);
                /// <summary>
                /// 暂时关闭路政无感支付
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "TempCloseRoadWGPay", "", "暂时关闭路政无感支付", "BOOL", "true", true);
                /// <summary>
                /// 关闭数据上传业务
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "TempCloseUpLoadData", "", "关闭数据上传业务", "BOOL", "false", true);
                /// <summary>
                /// 路政管控卡类
                /// </summary>
                //InitYardParams(Station_Id, Client_Id, "RoadCardTypeControl", "", "路政管控卡类", "STRING", @"1401,1409", true);
                /// <summary>
                /// 包月车位备案数
                /// </summary>
                //InitYardParams(Station_Id, Client_Id, "RoadMonthParkCount", "", "包月车位备案数", "INT", "0", true);
                /// <summary>
                /// 临停车位备案数
                /// </summary>
                //InitYardParams(Station_Id, Client_Id, "RoadTempParkCount", "", "临停车位备案数", "INT", "0", true);
                /// <summary>
                /// 启用进场排队功能
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "InYardLineUpEnable", "", "启用进场排队功能", "BOOL", "false", true);
                /// <summary>
                /// 启用无牌车检测功能
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "CheckGateStatusEnable", "", "启用无牌车检测功能", "BOOL", "false", true);
                /// <summary>
                /// 无牌车扫码确认开闸
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "NoPlateINOUTSubmitOpen", "", "无牌车扫码确认开闸", "BOOL", "false", true);
                /// <summary>
                /// 屏蔽收费界面返回场内
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "BackInYardEnable", "", "屏蔽收费界面返回场内", "BOOL", "false", true);
                /// <summary>
                /// 客户端在线支付统计提前付部分
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iStatisticsOnlinePay", "", "客户端在线支付统计提前付部分", "BOOL", "false", true);
                /// <summary>
                /// 重算费不报语音和刷新显示屏
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "iNoRefreshAgeCaleMoney", "", "重算费不报语音和刷新显示屏", "BOOL", "false", true);
                /// <summary>
                /// 收费车辆后车顶时前车默认返回场内
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "ClosefrmSubmitDefaultCancel", "", "收费车辆后车顶时前车默认返回场内", "BOOL", "false", true);
                /// <summary>
                /// 收费车辆后车顶是前车等待确认开闸
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "ClosefrmSubmitDefaultOpenGate", "", "收费车辆后车顶时前车等待确认开闸", "BOOL", "true", true);
                /// <summary>
                /// 包月车辆停大车场收费
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "MonthCardStopBigYardPay", "", "包月车辆停大车场收费", "BOOL", "false", true);
                /// <summary>
                /// 商业酒店模式(仅适用于临时车)
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "HotelPayModel", "", "商业酒店模式(仅适用于临时车)", "BOOL", "false", true);
                /// <summary>
                /// 允许双击画面开闸
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "AllowDoubleClickOpenGate", "", "允许双击画面开闸", "BOOL", "false", true);
                /// <summary>
                /// 开启会员免单
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "AllowVipFreeTime", "", "开启会员免单", "BOOL", "false", true);
                /// <summary>
                /// 开启对讲模式
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "AllowTalk", "", "开启对讲模式", "BOOL", "false", true);
                /// <summary>
                /// 无牌车自动进场
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "NoPlateDefualtIN", "", "无牌车自动进场", "BOOL", "false", true);
                /// <summary>
                /// 月卡超时收费（否-停止处理出场）
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "MonthCardPayOverTime", "", "月卡超时收费（否-停止处理出场）", "BOOL", "false", true);
                /// <summary>
                /// 显示屏车牌显示时间（秒）
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayShowTime", "", "显示屏车牌显示时间（秒）", "INT", "15", true);
                /// <summary>
                /// 确认开闸倒计时（秒）
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "SubmitOpenShowTime", "", "确认开闸倒计时（秒）", "INT", "30", true);
                /// <summary>
                /// 显示屏广告第一行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine1", "", "显示屏广告第一行", "STRING", @"自动识别", true);
                /// <summary>
                /// 显示屏广告第二行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine2", "", "显示屏广告第二行", "STRING", @"车辆缓行", true);
                /// <summary>
                /// 显示屏广告第三行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine3", "", "显示屏广告第三行", "STRING", @"一车一杆", true);
                /// <summary>
                /// 显示屏广告第四行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine4", "", "显示屏广告第四行", "STRING", @"请勿跟车", true);
                /// <summary>
                /// 显示屏广告第五行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine5", "", "显示屏广告第五行", "STRING", @"智慧停车", true);
                /// <summary>
                /// 显示屏广告第六行
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "DisplayLine6", "", "显示屏广告第六行", "STRING", @"与你同行", true);
                /// <summary>
                /// 停车券最大使用张数
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "FreeBillCanUseCount", "", "停车券最大使用张数", "INT", "99", true);
                /// <summary>
                /// 显示屏控制卡型号
                /// </summary>
                InitYardParams(Station_Id, Client_Id, "ControlCardModel", "", "显示屏控制卡型号", "STRING", "DUCP", true);
            }
            catch (Exception ex)
            {
            }
        }

        #endregion

        #region 添加优惠券数据
        /// <summary>
        /// 添加优惠券数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Dictionary<string, string> AddDiscountBills(TbDiscountBill input)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            SqlParameter[] param =
            {
                new SqlParameter("@Station_ID", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@TsaleId", System.Data.SqlDbType.BigInt), //商户ID
                new SqlParameter("@TbillNo", System.Data.SqlDbType.VarChar), //券号--券头
                new SqlParameter("@TbillName", System.Data.SqlDbType.NVarChar, 50), //券名
                new SqlParameter("@TbillInfor", System.Data.SqlDbType.VarChar,4000), //券说明
                new SqlParameter("@DiscountCount", System.Data.SqlDbType.VarChar), //优惠券数量
                new SqlParameter("@Tbedt", System.Data.SqlDbType.DateTime), //有效生效日期开始
                new SqlParameter("@Texdt", System.Data.SqlDbType.DateTime), //有效生效日期结束
                new SqlParameter("@TbillType", System.Data.SqlDbType.Int), //--免单类型 1停车券 2优惠券 3折扣券
                new SqlParameter("@TdeduType", System.Data.SqlDbType.Int), //--抵扣方式 1时间 2金额 4折扣
                new SqlParameter("@TdeduValue", System.Data.SqlDbType.Decimal),  //折扣值
                new SqlParameter("@TtermType", System.Data.SqlDbType.Int), //发行方式 1按有效期 2按领取时间开N日内有效 3按领取时间开始N小时内有效
                new SqlParameter("@TtermValue", System.Data.SqlDbType.Decimal), //发行价值
                new SqlParameter("@Tamount", System.Data.SqlDbType.Decimal), //每张券价值
                new SqlParameter("@TenantId", System.Data.SqlDbType.Int), //租户
                new SqlParameter("@CreatorUserId", System.Data.SqlDbType.BigInt), //添加用户
                new SqlParameter("@result",System.Data.SqlDbType.Int)  //返回值 


            };
            param[0].Value = input.Station_ID;
            param[1].Value = input.TsaleId;
            param[2].Value = input.TbillNo;
            param[3].Value = input.TbillName;
            param[4].Value = input.TbillInfor;
            param[5].Value = input.DiscountCount;
            param[6].Value = input.Tbedt;
            param[7].Value = input.Texdt;
            param[8].Value = input.TbillType;
            param[9].Value = input.TdeduType;
            param[10].Value = input.TdeduValue;
            param[11].Value = input.TtermType;
            param[12].Value = input.TtermValue;
            param[13].Value = input.Tamount;
            param[14].Value = input.TenantId;
            param[15].Value = input.TcreateOpId;
            param[16].Direction = ParameterDirection.Output;
            SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "Add_TB_DiscountBill_SML", param);
            if (Convert.ToInt32(param[16].Value) == 1)
            {
                result.Add("retype", "1");
                result.Add("revalue", "生成优惠券成功");
            }
            else if (Convert.ToInt32(param[16].Value) == -2)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "生成张数不能大于1000张");
            }
            else if (Convert.ToInt32(param[16].Value) == -3)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "1小时内只能生成一次");
            }
            else
            {
                result.Add("retype", "-1");
                result.Add("revalue", "生成优惠券失败");
            }
            return result;
        }

        #endregion

        #region 查询优惠券数据
        /// <summary>
        /// 查询优惠券数据
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <returns></returns>
        public List<TbDiscountBillDb> GetTbDiscountBillTable(long Station_ID)
        {
            List<TbDiscountBillDb> spAll = new List<TbDiscountBillDb>();
            string strSql = string.Format("Select * from Tb_DiscountBill_VML Where IsDeleted=0 AND Station_ID={0}", Station_ID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbDiscountBillDb>(dt);
            }
            return spAll;
        }

        #endregion

        #region 查询基础资料数据
        public List<TbObjects> GetTbObjects(List<long> Station_ID, string FilterText)
        {
            List<TbObjects> spAll = new List<TbObjects>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND ([OBJ_Name] like N'%{0}%' or [OBJ_DESC] like N'%{0}%')",
                    FilterText);
            }
            string strSql = string.Format("Select * from Tb_Objects Where IsDeleted=0 AND Station_ID in ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbObjects>(dt);
            }
            return spAll;
        }
        #endregion

        #region 获取停车场场所信息
        public List<TbStation> GetTbStations(long Station_ID)
        {
            List<TbStation> spAll = new List<TbStation>();


            string strSql = string.Format("Select * from Tb_Station Where IsDeleted=0 AND [Station_Stop]=0 AND Station_ID={0} and [Station_Type]<>N'机构银行' and Station_Type<>N'公司机构' ", Station_ID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbStation>(dt);
            }
            return spAll;
        }
        #endregion

        #region 获取ICP信息
        public string GetICPfiling()
        {
            string strSql = "select top 1 isnull(value,N'') value FROM [ABP].[Settings] where Name='App.Tenant.IPCfiling'";
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["value"].ToString();
            }
            return "未设置ICP信息";
        }
        #endregion

        #region 根据用户编号获取组织编号
        public long GetCurrenUserOrganizationUnit(long userId)
        {
            string strSql = string.Format("Select [OrganizationUnitId] from [ABP].[UserOrganizationUnits] Where IsDeleted=0  AND [UserId]={0}  ", userId);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return long.Parse(dt.Rows[0]["OrganizationUnitId"].ToString());
            }
            return 0;
        }
        #endregion

        #region 根据用户编号获取组织编号及子项
        public List<long> GetCurrenUserOrganizationAndChildrenUnit(long userId)
        {
            string strSql = string.Format("exec O_GetCurrentUserOrgList {0}   ", userId);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                List<long> result = new List<long>();
                foreach (DataRow row in dt.Rows)
                {
                    result.Add(long.Parse(row["Station_ID"].ToString()));
                }
                return result;
            }
            return null;
        }
        public List<TbStationTreeDto> GetCurrenUserOrganizationAndChildrenUnitResultDto(long userId)
        {
            string strSql = string.Format("exec O_GetCurrentUserOrgList {0}   ", userId);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                List<TbStationTreeDto> result = new List<TbStationTreeDto>();
                foreach (DataRow row in dt.Rows)
                {
                    TbStationTreeDto dto = new TbStationTreeDto();
                    dto.Station_Id = long.Parse(row["Station_ID"].ToString());
                    dto.Level = int.Parse(row["Level"].ToString());
                    dto.ParentId = Convert.ToInt64(row["ParentId"]);
                    dto.Station_Name = row["Station_Name"].ToString();
                    dto.Station_No = row["Station_No"].ToString();
                    dto.Station_Type = row["Station_Type"].ToString();
                    result.Add(dto);
                }
                return result;
            }
            return null;
        }
        #endregion

        #region 返回组织NO
        public string GetTbObject_NO(long Station_ID)
        {
            string strSql = string.Format("SELECT Station_No FROM [dbo].[Tb_Station] WHERE Station_ID={0}", Station_ID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0][0].ToString().Trim();
            }
            else
                return "";
        }
        #endregion

        #region 查询客户端数据
        public List<TbClientRegister> GetTbClientRegister(List<long> Station_ID, string FilterText)
        {
            List<TbClientRegister> spAll = new List<TbClientRegister>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND ([Client_ID]='{0}' or Client_Name like N'%{0}%' or [Client_Type] like N'%{0}%')",
                    FilterText);
            }
            string strSql = "";
            if (Station_ID != null)
            {
                strSql = string.Format("Select * from [Tb_ClientRegister] Where IsDeleted=0 AND Station_ID in ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            }
            else
            {
                strSql = string.Format("Select * from [Tb_ClientRegister] Where IsDeleted=0 {0}", strWhere);

            }
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbClientRegister>(dt);
            }
            return spAll;
        }
        #endregion

        #region 查询岗亭操作用户 
        public List<TbrGTOpUser> GetTbGTUser(List<long> Station_ID)
        {
            List<TbrGTOpUser> spAll = new List<TbrGTOpUser>();
            string strSql = "SELECT * FROM (SELECT A.*,C.Station_Id AS Station_Id,C.[Station_No],C.[Station_Name],ISNULL(Station_Validity,DATEADD(day,7,CONVERT(VARCHAR(10),GETDATE(),120))) Station_Validity FROM ("
                                + " SELECT A.Id, A.UserName, "
                                + " ISNULL(EmailAddress, UserName) EmailAddress ,Password,ISNULL(PhoneNumber, N'') PhoneNumber, A.TenantId,A.IsLockoutEnabled"
                                + " FROM ABP.Users A LEFT JOIN ABP.UserRoles B ON A.ID = B.UserId AND A.TenantId = B.TenantId LEFT JOIN[ABP].[Roles]"
                                + " C"
                                + " ON B.[RoleId]=C.[Id] AND B.TenantId=C.TenantId WHERE  C.ID IS NOT NULL AND C.[IsDeleted]= 0 AND C.[DisplayName] LIKE N'%岗亭操作员'  "
                                + "  AND A.IsDeleted = 0 AND A.IsActive = 1   "
                                + " ) A LEFT JOIN [ABP].[UserOrganizationUnits] B ON A.Id = B.UserId AND A.TenantId = B.TenantId"
                                + " LEFT JOIN dbo.tB_Station C ON B.OrganizationUnitId = C.Station_Id AND B.TenantId = C.TenantId"
                                + " WHERE B.OrganizationUnitId IS NOT NULL AND B.IsDeleted = 0 AND C.Station_Id IS NOT NULL AND C.IsDeleted = 0) A WHERE 1=1   ";
            ;
            if (Station_ID != null)
            {
                strSql = string.Format(strSql + " AND Station_ID in ({0}) ", string.Join(",", Station_ID.ToArray()));
            }
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    TbrGTOpUser tbrGTOp = new TbrGTOpUser();
                    tbrGTOp.UserName = row["UserName"].ToString();
                    if (row["EmailAddress"].ToString().IndexOf("@") >= 1)
                    {
                        tbrGTOp.EmailAddress = row["EmailAddress"].ToString().Substring(0, row["EmailAddress"].ToString().IndexOf("@"));
                    }
                    else
                    {
                        tbrGTOp.EmailAddress = row["EmailAddress"].ToString();
                    }
                    spAll.Add(tbrGTOp);
                }
            }
            return spAll;
        }
        #endregion

        #region 查询收费类型 
        public List<string> GetTbCardType(List<long> Station_ID)
        {
            List<string> spAll = new List<string>();
            string strSql = $@"SELECT N'全部' OBJ_DESC  UNION ALL SELECT OBJ_DESC FROM Tb_Objects WHERE OBJ_TYPE=5 ";
            ;
            if (Station_ID != null)
            {
                strSql = string.Format(strSql + " AND Station_ID in ({0}) ", string.Join(",", Station_ID.ToArray()));
            }
            strSql = strSql + "  UNION ALL SELECT N'取消记录' OBJ_DESC  ";
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                { 
                    spAll.Add(row["OBJ_DESC"].ToString());
                }
            }
            return spAll;
        }
        #endregion

        #region 查询出场通道 
        public List<TbrOutMach> GetOutMach(List<long> Station_ID)
        {
            List<TbrOutMach> spAll = new List<TbrOutMach>();
            if (Station_ID == null || Station_ID.Count <= 0 || Station_ID[0] == 0)
            {
                return null;
            }
            string strSql = "declare @Station_No nvarchar(50) "
            + " SELECT @Station_No = Station_No FROM Tb_Station WHERE Station_ID =  " + Station_ID[0].ToString()
            + " EXEC('SELECT distinct tOut_Mach_Name FROM tY_OutYard_' + @Station_No) ";
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    TbrOutMach outMach = new TbrOutMach();
                    outMach.MachName = row["tOut_Mach_Name"].ToString();
                    spAll.Add(outMach);
                }
            }
            return spAll;
        }
        #endregion

        #region 获取当前场所所有部门信息
        public List<TbrYardDepart> GetDepartList(List<long> Station_ID)
        {
            List<TbrYardDepart> spAll = new List<TbrYardDepart>();
            if (Station_ID == null || Station_ID.Count <= 0 || Station_ID[0] == 0)
            {
                return null;
            }
            string strSql = "SELECT Id,[Depart_Name] FROM [dbo].[Tb_Depart] WHERE [IsDeleted]=0 AND Station_ID in (" + string.Join(",", Station_ID.ToArray()).Trim(',') + ") ";
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    TbrYardDepart depart = new TbrYardDepart();
                    depart.Id = long.Parse(row["Id"].ToString());
                    depart.Depart_Name = row["Depart_Name"].ToString();
                    spAll.Add(depart);
                }
            }
            return spAll;
        }
        #endregion

        #region 检查是否外键
        public bool CheckIsForeignKey(long Id, long Station_Id, string TableName)
        {
            try
            {
                string strSql = "Exec O_CheckIsForeignKey '" + TableName + "'," + Id + "," + Station_Id;
                DataSet dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql);
                if (dt != null && dt.Tables != null && dt.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                return false;
            }
            catch
            { return false; }
        }
        #endregion

        #region 检查角色是否存在权限
        public bool CheckIsAbpAuthorize(long UserId, string Authorize)
        {
            try
            {
                string strSql = "select * from  [ABP].[Permissions] WHERE RoleId=(select TOP 1 RoleId from [ABP].[UserRoles] WHERE UserId=" + UserId + " AND TenantId=2) AND IsGranted=1 AND Name='" + Authorize + "'";
                DataSet dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql);
                if (dt != null && dt.Tables != null && dt.Tables[0] != null && dt.Tables[0].Rows.Count > 0)
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 车位管理查询
        public List<TbYardUserParkingVML> GetTbYardUserParkinr(List<long> Station_ID, string FilterText)
        {
            List<TbYardUserParkingVML> spAll = new List<TbYardUserParkingVML>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND ([User_No]='{0}' or User_Name like N'%{0}%' or [CUR_PLATENO] like N'%{0}%')",
                    FilterText);
            }
            string strSql = string.Format("Select * from [Tb_YardUserParking_VML] Where IsDeleted=0 and Station_ID in ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbYardUserParkingVML>(dt);
            }
            return spAll;
        }
        #endregion

        #region 黑名单查询
        public List<TbYardBlackListVML> GetTbYardBlackList(List<long> Station_ID, string FilterText)
        {
            List<TbYardBlackListVML> spAll = new List<TbYardBlackListVML>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND (OBJ_Name like N'%{0}%' or [CardNo] like N'%{0}%')",
                    FilterText);
            }
            string strSql = string.Format("Select * from [Tb_YardBlackList_VML] Where IsDeleted=0 and Station_ID IN ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbYardBlackListVML>(dt);
            }
            return spAll;
        }
        #endregion

        #region 亲情名单查询
        public List<TbYardLovingListVML> GetTbYardLovingList(List<long> Station_ID, string FilterText)
        {
            List<TbYardLovingListVML> spAll = new List<TbYardLovingListVML>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND (OBJ_Name like N'%{0}%' or [CardNo] like N'%{0}%')",
                    FilterText);
            }
            string strSql = string.Format("Select * from [Tb_YardLovingList_VML] Where IsDeleted=0 and Station_ID IN ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbYardLovingListVML>(dt);
            }
            return spAll;
        }
        #endregion

        #region 月卡分时
        public List<TbYardPayMonthCardVML> GetTbYardPayMonthCard(List<long> Station_ID, long Id, string FilterText)
        {
            List<TbYardPayMonthCardVML> spAll = new List<TbYardPayMonthCardVML>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(FilterText))
            {
                strWhere = string.Format(" AND (CardType like N'%{0}%')",
                    FilterText);
            }
            string strSql = string.Format("Select * from [Tb_YardPayMonthCard_VML] Where IsDeleted=0 and Station_ID IN ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            if (Id != 0)
            {
                strWhere = string.Format(" AND Id={0}",
                       Id.ToString());
                strSql = string.Format("Select * from [Tb_YardPayMonthCard_VML] Where IsDeleted=0 and Station_ID IN ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            }
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbYardPayMonthCardVML>(dt);
            }
            return spAll;
        }
        public bool UpdatePayMonthCard(int CardTypeId, string CardTypeName, long StationId, DateTime BTime, DateTime ETime)
        {
            try
            {
                string strSql = " if exists(select 0 from [dbo].[tB_YardPayZMonthCard] where Station_Id=" + StationId + " AND CardTypeID=" + CardTypeId + " AND CardType=N'" + CardTypeName + "')"
                                + " begin"
                                + " UPDATE[tB_YardPayZMonthCard] SET MCardBTime = '1970-01-01 " + BTime.ToString("HH:mm:ss") + "',MCardETime='1970-01-01 " + ETime.ToString("HH:mm:ss") + "' WHERE Station_Id = " + StationId + " AND CardTypeID = " + CardTypeId + " AND CardType = N'" + CardTypeName + "'"
                                + " end"
                                + " else"
                                + " begin"
                                + " INSERT INTO[dbo].[tB_YardPayZMonthCard]"
                                + " ([Station_Id]"
                                + " ,[CardTypeID]"
                                + " ,[CardType]"
                                + " ,[MCardBTime]"
                                + " ,[MCardETime]"
                                + " ,[CreationTime]"
                                + " ,[CreatorUserId]"
                                + " ,[LastModificationTime]"
                                + " ,[LastModifierUserId]"
                                + " ,[IsDeleted]"
                                + " ,[DeleterUserId]"
                                + " ,[DeletionTime]"
                                + " ,[TenantId])"
                                + " VALUES"
                                + " (" + StationId + ""
                                + " , " + CardTypeId + ""
                                + " , N'" + CardTypeName + "'"
                                + " , '1970-01-01 " + BTime.ToString("HH:mm:ss") + "'"
                                + " , '1970-01-01 " + ETime.ToString("HH:mm:ss") + "'"
                                + " , GETDATE()"
                                + " , 0"
                                + " , NULL"
                                + " , NULL"
                                + " , 0"
                                + " , NULL"
                                + " , NULL"
                                + " , 2)"
                                + " end";
                return SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 查询优惠券主表数据
        /// <summary>
        /// 查询优惠券主表数据
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <param name="FilterText"></param>
        /// <param name="SaleID">如是0则查询此组织，如大于0则查询此商户</param>
        /// <returns></returns>
        public List<TbDiscountBillMaster> GetTbDiscountBillMaster(List<long> Station_ID, string FilterText, int SaleID)
        {
            BillFilterText billFilterText = FilterText.ToObject<BillFilterText>();
            List<TbDiscountBillMaster> spAll = new List<TbDiscountBillMaster>();
            string strWhere = "";
            if (!string.IsNullOrEmpty(billFilterText.FilterText))
            {
                strWhere = string.Format(" AND (Sale_No = N'{0}' or [Sale_Name] like N'%{0}%')  ",
                    billFilterText.FilterText);
            }
            if (!billFilterText.hadRecvOver)
            {
                strWhere = strWhere + " AND [DiscountCount]<>yLQ ";
            }
            if (!billFilterText.hadOverTime)
            {
                strWhere = strWhere + " AND ((CONVERT(VARCHAR(8),[InsertTime],114)='00:00:00' AND Texdt>=GETDATE()) OR (CONVERT(VARCHAR(8),[InsertTime],114)<>'00:00:00' AND 1=1)) ";
            }
            if (SaleID > 0)
            {
                strWhere += string.Format(" AND tSaleId={0}", SaleID);
            }
            string strSql = string.Format("Select * from [Tb_DiscountBillMaster_VML] Where Station_ID in ({0}) {1}", string.Join(",", Station_ID.ToArray()), strWhere);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbDiscountBillMaster>(dt);
            }
            return spAll;
        }

        public TbDiscountBillMaster GetTbDiscountBillMasterById(long Id)
        {
            List<TbDiscountBillMaster> spAll = new List<TbDiscountBillMaster>();
            string strSql = string.Format("Select * from Tb_DiscountBillMaster_VML where Id={0}", Id);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbDiscountBillMaster>(dt);
                return spAll[0];
            }
            else
            {
                return new TbDiscountBillMaster();
            }

        }
        /// <summary>
        /// 删除券
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool DeleteDiscountBill(long Id, long? UserId, bool isAll)
        {
            string strSql = "UPDATE Tb_DiscountBill SET  IsDeleted=1,DeleterUserId=" + (UserId == null ? "6" : UserId.ToString()) + ",DeletionTime=GETDATE() WHERE DisID=("
                            + " Select Id from Tb_DiscountBillMaster_VML where id = " + Id + " and tSalePayStatus = 1 and ySy = 0 and yLq = 0"
                            + " ) and Station_ID =  (Select Station_ID from Tb_DiscountBillMaster_VML where id =  " + Id + "  and tSalePayStatus = 1 "
                            + " and ySy = 0 and yLq = 0) and tSaleId = (Select tSaleId from Tb_DiscountBillMaster_VML where id =  " + Id + "  and tSalePayStatus = 1 and ySy = 0 and yLq = 0)";
            if (isAll)
            {
                strSql = "UPDATE Tb_DiscountBill SET IsDeleted = 1, DeleterUserId = " + (UserId == null ? "6" : UserId.ToString()) + ",DeletionTime = GETDATE() WHERE DisID =" + Id;
            }
            return SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) > 0;
        }
        /// <summary>
        /// 删除券
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool DeleteDiscountBill(List<long> Id, long? UserId)
        {
            string strSql = "UPDATE Tb_DiscountBill SET  IsDeleted=1,DeleterUserId=" + (UserId == null ? "6" : UserId.ToString()) + ",DeletionTime=GETDATE() WHERE tUseStatus=1 and tRecvTime is null and  Id in (" + string.Join(",", Id.ToArray()) + ")";
            return SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) > 0;
        }
        #endregion

        #region 判断是否是商户且是否是组织
        /// <summary>
        /// 判断是否是商户且是否是组织
        /// </summary>
        /// <param name="UserID">登录用户ID</param>
        /// <returns>返回商户ID,如果没有则返回0</returns>
        public int IsUserOrganizationUnit(long UserID)
        {
            string strSql = string.Format("SELECT * FROM [ABP_Users_VML] WHERE id={0}", UserID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                string SaleID = dt.Rows[0]["SaleID"].ToString().Trim();
                if (!string.IsNullOrEmpty(SaleID))
                { return Convert.ToInt32(SaleID); }
                else
                { return 0; }
            }
            else
            {
                return -1;
            }
        }
        #endregion

        #region 判断是否有B账查看权限
        public bool isBAccountQuery(long userId)
        {
            try
            {
                string strSql = " SELECT A.Name RoleName,A.IsGranted,A.RoleId,B.Id UserId FROM [ABP].[Permissions] A RIGHT JOIN  ( "
                               + " SELECT Id, RoleId FROM(SELECT A.*, C.Station_Id AS Station_Id, C.[Station_No], C.[Station_Name] FROM(SELECT A.Id, A.UserName, "
                               + " ISNULL(EmailAddress, UserName) EmailAddress, Password, ISNULL(PhoneNumber, N'') PhoneNumber, "
                               + " A.TenantId, ISNULL(A.IsLockoutEnabled, 0) IsLockoutEnabled, ISNULL(A.IsActive, 0) IsActive, ISNULL(A.IsDeleted, 0) IsDeleted, C.[Id] RoleId, C.[DisplayName] RoleName "
                               + " FROM ABP.Users A LEFT JOIN ABP.UserRoles B ON A.ID = B.UserId AND A.TenantId = B.TenantId LEFT JOIN [ABP].[Roles] "
                               + " C "
                               + " ON B.[RoleId] = C.[Id] AND B.TenantId = C.TenantId WHERE A.Id="+userId+" AND  C.ID IS NOT NULL AND C.[IsDeleted] = 0 "
                               + " ) A LEFT JOIN [ABP].[UserOrganizationUnits] B ON A.Id = B.UserId AND A.TenantId = B.TenantId "
                               + " LEFT JOIN dbo.tB_Station C ON B.OrganizationUnitId = C.Station_Id AND B.TenantId = C.TenantId "
                               + " WHERE B.OrganizationUnitId IS NOT NULL AND B.IsDeleted = 0 AND C.Station_Id IS NOT NULL AND C.IsDeleted = 0) A   "
                               + " ) B ON A.RoleId = B.RoleId "
                               + " WHERE A.Id IS NOT NULL  AND IsGranted=1  AND (A.Name='Pages.Administration.Tenant.QueryBAccount' or A.Name='Pages.Administration.Host.QueryBAccount')";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 判断当前发行记录是否为隐藏记录
        public bool isHideIssuedRecord(long IssuedId,long StationId)
        {
            try
            {
                string strSql = " if exists(select Station_ID,Station_No,Station_Name from Tb_Station where Station_No in ( "
                                + " select replace(replace(name,'v_OutYard_',''),'_HIDE','') from sys.all_objects where type = 'V' and name like 'v_OutYard_%_HIDE')  and Station_ID = " + StationId + ")"
                                + " BEGIN"
                                + " DECLARE @STATIONNO NVARCHAR(50) "
                                + " DECLARE @SQL NVARCHAR(2000) "
                                + " SELECT @STATIONNO = Station_No FROM Tb_Station WHERE Station_ID = " + StationId + " "
                                + " SET @SQL=N'SELECT Issued FROM tY_AccIssued_'+@STATIONNO+N' WHERE ACC=1 AND Issued=" + IssuedId + "'"
                                + " EXEC(@SQL)"
                                + " END ";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 保存当前发行记录为隐藏记录
        public bool saveHideIssuedRecord(long IssuedId, long StationId,int ACC)
        {
            try
            {
                string strSql = " if exists(select Station_ID,Station_No,Station_Name from Tb_Station where Station_No in ( "
                                + " select replace(replace(name,'v_OutYard_',''),'_HIDE','') from sys.all_objects where type = 'V' and name like 'v_OutYard_%_HIDE')  and Station_ID = " + StationId + ")"
                                + " BEGIN"
                                + " DECLARE @STATIONNO NVARCHAR(50) "
                                + " DECLARE @SQL NVARCHAR(2000) "
                                + " SELECT @STATIONNO = Station_No FROM Tb_Station WHERE Station_ID = " + StationId + " "
                                + " SET @SQL=N'EXEC [p_SycAccRecord] '+convert(varchar(20),@STATIONNO)+'," + IssuedId + "," + ACC + ",''Issued'',''insert'''"
                                + " EXEC(@SQL)"
                                + " END ";
                SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql);

                return true;

            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 报表中心

        #region 进场报表

        #region 进场数据
        public DataSet GetTbrInYardDB(TbrInYardInput pc, bool NoBAccount)
        {
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@Station_No", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@IN_TIME1", System.Data.SqlDbType.DateTime), //进场时间
                new SqlParameter("@IN_TIME2", System.Data.SqlDbType.DateTime), //进场时间              
                new SqlParameter("@ClassId", System.Data.SqlDbType.Int), //班次号
                new SqlParameter("@OP_Name", System.Data.SqlDbType.NVarChar,50), //操作员
                new SqlParameter("@Mach_Name", System.Data.SqlDbType.NVarChar,50), //通道设备号           
                new SqlParameter("@NoPlate", System.Data.SqlDbType.Bit),  //无牌车
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar,500), //车牌号码
                new SqlParameter("@CarPlace", System.Data.SqlDbType.NVarChar,500), //车位位置
                new SqlParameter("@Small", System.Data.SqlDbType.Int), //小车场记录
                new SqlParameter("@InYard", System.Data.SqlDbType.Int), //场内车0否1是2全部
                new SqlParameter("@isDelete", System.Data.SqlDbType.Int), /*0未删除1已删除2全部*/
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = pc.Station_No;
            param[2].Value = pc.IN_TIME1;
            param[3].Value = pc.IN_TIME2;
            param[4].Value = pc.ClassId;
            param[5].Value = string.IsNullOrEmpty(pc.OP_Name) ? "" : pc.OP_Name;
            param[6].Value = string.IsNullOrEmpty(pc.Mach_Name) ? "" : pc.Mach_Name;
            param[7].Value = pc.NoPlate;
            param[8].Value = string.IsNullOrEmpty(pc.PlateNo) ? "" : pc.PlateNo;  //pc.PlateNo;
            param[9].Value = string.IsNullOrEmpty(pc.CarPlace) ? "" : pc.CarPlace;  //pc.CarPlace;
            param[10].Value = pc.Small;
            param[11].Value = pc.InYard;
            param[12].Value = pc.isDelete;
            param[13].Value = (NoBAccount ? 1 : 0);
            param[14].Value = pc.Export;
            param[15].Value = pc.PageSize;
            param[16].Value = pc.PageIndex;
            param[17].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[18].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc; 
            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_InYard", param);
        }
        #endregion

        #region 进场数据
        public DataSet GetInYardSql(TbrInYardInput pc, bool NoBAccount)
        {
            string strSql = "select * from tY_InYard_" + pc.Station_No + " where tIN_ID not in (select tIN_ID from tY_OutYard_" + pc.Station_No + ") and tIN_Time>='" + pc.IN_TIME1?.ToString("yyyy-MM-dd HH:mm:ss") + "' " +
                " and tIN_Time<='" + pc.IN_TIME2?.ToString("yyyy-MM-dd 23:59:59") + "'" +
                " and tIN_Image5 = '' order by tIN_Time";
            return SqlHelper.ExecuteDataset(GetCon(), CommandType.Text, strSql);
        }
        #endregion

        #region 车辆进场查询
        public YardPagedResult<TbrInYard> GetTbrInYard(TbrInYardInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrInYard> result = new YardPagedResult<TbrInYard>();

            DataSet ds = GetTbrInYardDB(pc, NoBAccount);

            if (ds.Tables.Count == 2)
            {
                List<TbrInYard> li = DataTableExtend.ToDataList<TbrInYard>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result; 
        }
        #endregion

        #region 车辆进场导出
        public List<TbrInYard> ExportTbrInYard(TbrInYardInput pc, bool NoBAccount)
        {
            List<TbrInYard> result = new List<TbrInYard>();
              
            DataSet ds = GetTbrInYardDB(pc, NoBAccount); 
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrInYard>(ds.Tables[0]);
            }
            return result;

        }
        #endregion

        #region 场内记录导出
        public List<TbrInYardSql> ExportInYardSql(TbrInYardInput pc, bool NoBAccount)
        {
            List<TbrInYardSql> result = new List<TbrInYardSql>();

            DataSet ds = GetInYardSql(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrInYardSql>(ds.Tables[0]);
            }
            return result;

        }
        #endregion

        #endregion

        #region 出场波表

        #region 出场数据
        public DataSet GetTbrOutYardDB(TbrOutYardInput pc, bool NoBAccount)
        {
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@Station_No", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@IN_TIME1", System.Data.SqlDbType.DateTime), //进场时间
                new SqlParameter("@IN_TIME2", System.Data.SqlDbType.DateTime), //进场时间    
                new SqlParameter("@OUT_TIME1", System.Data.SqlDbType.DateTime), //出场时间
                new SqlParameter("@OUT_TIME2", System.Data.SqlDbType.DateTime), //出场时间     
                new SqlParameter("@ClassId", System.Data.SqlDbType.Int), //班次号
                new SqlParameter("@OP_Name", System.Data.SqlDbType.NVarChar,50), //操作员
                new SqlParameter("@Mach_Name", System.Data.SqlDbType.NVarChar,50), //通道设备号           
                new SqlParameter("@NoPlate", System.Data.SqlDbType.Bit),  //无牌车
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar,500), //车牌号码
                new SqlParameter("@CarPlace", System.Data.SqlDbType.NVarChar,500), //车位位置
                new SqlParameter("@YS", System.Data.SqlDbType.Int), /*是否收费 0不收费记录 1收费记录 2全部*/
                new SqlParameter("@Small", System.Data.SqlDbType.Int), //小车场记录
                new SqlParameter("@Charge", System.Data.SqlDbType.Int), //充电记录
                new SqlParameter("@CardType", System.Data.SqlDbType.NVarChar,500), //收费类型
                new SqlParameter("@IsDelete", System.Data.SqlDbType.Int), //小车场记录
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@OnlyAccount",System.Data.SqlDbType.Int),//仅显示隐藏记录
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //导出
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = pc.Station_No;
            param[2].Value = pc.IN_TIME1;
            param[3].Value = pc.IN_TIME2;
            param[4].Value = pc.OUT_TIME1;
            param[5].Value = pc.OUT_TIME2;
            param[6].Value = pc.ClassId;
            param[7].Value = string.IsNullOrEmpty(pc.OP_Name) ? "" : pc.OP_Name;
            param[8].Value = string.IsNullOrEmpty(pc.Mach_Name) ? "" : pc.Mach_Name;
            param[9].Value = pc.NoPlate;
            param[10].Value = string.IsNullOrEmpty(pc.PlateNo) ? "" : pc.PlateNo;  //pc.PlateNo;
            param[11].Value = string.IsNullOrEmpty(pc.CarPlace) ? "" : pc.CarPlace;  //pc.CarPlace;
            param[12].Value = pc.YS;
            param[13].Value = pc.Small;
            param[14].Value = pc.Charge;
            param[15].Value = pc.CardType;
            param[16].Value = pc.IsDelete;
            param[17].Value = (NoBAccount ? 1 : 0);
            param[18].Value = pc.isOnlyShowHideRecord;
            param[19].Value = pc.Export;
            param[20].Value = pc.PageSize;
            param[21].Value = pc.PageIndex;
            param[22].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[23].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_OutYard", param);
        }
        #endregion

        #region 车辆出场查询
        public YardPagedResult<TbrOutYard> GetTbrOutYard(TbrOutYardInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrOutYard> result = new YardPagedResult<TbrOutYard>(); 
            DataSet ds = GetTbrOutYardDB(pc, NoBAccount);
            if (ds.Tables.Count == 2)
            {
                List<TbrOutYard> li = DataTableExtend.ToDataList<TbrOutYard>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result;

        }
        #endregion

        #region 车辆出场导出
        public List<TbrOutYard> ExportTbrOutYard(TbrOutYardInput pc, bool NoBAccount)
        {
            List<TbrOutYard> result = new List<TbrOutYard>();
            DataSet ds = GetTbrOutYardDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrOutYard>(ds.Tables[0]);
            }
            return result;

        }
        #endregion

        #endregion

        #region 出场报表版本2

        #region 出场数据版本2
        public DataSet GetTbrOutYard2DB(TbrOutYardInput2 pc, bool NoBAccount)
        {
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@Station_No", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@IN_TIME1", System.Data.SqlDbType.DateTime), //进场时间
                new SqlParameter("@IN_TIME2", System.Data.SqlDbType.DateTime), //进场时间    
                new SqlParameter("@OUT_TIME1", System.Data.SqlDbType.DateTime), //出场时间
                new SqlParameter("@OUT_TIME2", System.Data.SqlDbType.DateTime), //出场时间     
                new SqlParameter("@ClassId", System.Data.SqlDbType.Int), //班次号
                new SqlParameter("@OP_Name", System.Data.SqlDbType.NVarChar,50), //操作员
                new SqlParameter("@Mach_Name", System.Data.SqlDbType.NVarChar,50), //通道设备号           
                new SqlParameter("@NoPlate", System.Data.SqlDbType.Bit),  //无牌车
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar,500), //车牌号码
                new SqlParameter("@CarPlace", System.Data.SqlDbType.NVarChar,500), //车位位置
                new SqlParameter("@YS", System.Data.SqlDbType.Int), /*是否收费 0不收费记录 1收费记录 2全部*/
                new SqlParameter("@Small", System.Data.SqlDbType.Int), //小车场记录
                new SqlParameter("@Charge", System.Data.SqlDbType.Int), //充电记录
                new SqlParameter("@BillName", System.Data.SqlDbType.NVarChar,50), //免单券名称
                new SqlParameter("@CardType", System.Data.SqlDbType.NVarChar,500), //收费类型
                new SqlParameter("@IsDelete", System.Data.SqlDbType.Int), //删除记录
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@OnlyAccount",System.Data.SqlDbType.Int),//仅显示隐藏记录
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //导出
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = pc.Station_No;
            param[2].Value = pc.IN_TIME1;
            param[3].Value = pc.IN_TIME2;
            param[4].Value = pc.OUT_TIME1;
            param[5].Value = pc.OUT_TIME2;
            param[6].Value = pc.ClassId;
            param[7].Value = string.IsNullOrEmpty(pc.OP_Name) ? "" : pc.OP_Name;
            param[8].Value = string.IsNullOrEmpty(pc.Mach_Name) ? "" : pc.Mach_Name;
            param[9].Value = pc.NoPlate;
            param[10].Value = string.IsNullOrEmpty(pc.PlateNo) ? "" : pc.PlateNo;  //pc.PlateNo;
            param[11].Value = string.IsNullOrEmpty(pc.CarPlace) ? "" : pc.CarPlace;  //pc.CarPlace;
            param[12].Value = pc.YS;
            param[13].Value = pc.Small;
            param[14].Value = pc.Charge;
            param[15].Value = pc.BillName;
            param[16].Value = pc.CardType;
            param[17].Value = pc.IsDelete;
            param[18].Value = (NoBAccount ? 1 : 0);
            param[19].Value = pc.isOnlyShowHideRecord;
            param[20].Value = pc.Export;
            param[21].Value = pc.PageSize;
            param[22].Value = pc.PageIndex;
            param[23].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[24].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_OutYardV2", param);
        }
        #endregion

        #region 车辆出场查询版本2
        public YardPagedResult2<DataTable> GetTbrOutYard2(TbrOutYardInput2 pc, bool NoBAccount)
        {
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>(); 
            DataSet ds = GetTbrOutYard2DB(pc, NoBAccount);
            if (ds.Tables.Count == 4)
            {
                DataTable li = ds.Tables[0];
                DataTable li2 = ds.Tables[2];
                DataTable li3 = ds.Tables[3];
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
                result.s = li2;
                result.o = li3;
            }
            return result;

        }
        #endregion

        #region 车辆出场导出版本2
        public DataTable ExportTbrOutYard2(TbrOutYardInput2 pc, bool NoBAccount)
        {
            DataTable result = new DataTable();
            DataSet ds = GetTbrOutYard2DB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = ds.Tables[0];
            }
            return result;

        }
        #endregion

        #endregion

        #region 车辆开闸

        #region 开闸数据
        public DataSet GetTbrOpenGateDB(TbrOpenGateInput pc)
        {
             
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@TIME1", System.Data.SqlDbType.DateTime), //开闸时间
                new SqlParameter("@TIME2", System.Data.SqlDbType.DateTime), //开闸时间  
                new SqlParameter("@Mach_Name", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.TIME1;
            param[2].Value = pc.TIME2;
            param[3].Value = string.IsNullOrEmpty(pc.Mach_Name) ? "" : pc.Mach_Name;
            param[4].Value = pc.Export;
            param[5].Value = pc.PageSize;
            param[6].Value = pc.PageIndex;
            param[7].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[8].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_OpenGate", param);
             
        }
        #endregion

        #region 车辆开闸查询
        public YardPagedResult<TbrOpenGate> GetTbrOpenGate(TbrOpenGateInput pc)
        {
            YardPagedResult<TbrOpenGate> result = new YardPagedResult<TbrOpenGate>();
            DataSet ds = GetTbrOpenGateDB(pc);
            if (ds.Tables.Count == 2)
            {
                List<TbrOpenGate> li = DataTableExtend.ToDataList<TbrOpenGate>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 车辆开闸导出
        public List<TbrOpenGate> ExportTbrOpenGate(TbrOpenGateInput pc)
        {
            List<TbrOpenGate> result = new List<TbrOpenGate>(); 
            DataSet ds = GetTbrOpenGateDB(pc);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrOpenGate>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 车辆操作报表

        #region 车辆操作数据
        public DataSet GetTbrIssuedOpCardDB(TbrIssuedOpCardInput pc, bool NoBAccount)
        {
             
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar), //车牌号码
                new SqlParameter("@UserName", System.Data.SqlDbType.NVarChar), //车主姓名
                new SqlParameter("@CardTypeId", System.Data.SqlDbType.NVarChar), //卡类编号1401这类
                new SqlParameter("@EndTime1", System.Data.SqlDbType.DateTime), //操作时间
                new SqlParameter("@EndTime2", System.Data.SqlDbType.DateTime), //操作时间  
                new SqlParameter("@OpType", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@OnlyAccount",System.Data.SqlDbType.Int),//B账查询 
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = string.IsNullOrEmpty(pc.PlateNo) ? "" : pc.PlateNo;  //pc.PlateNo;
            param[2].Value = string.IsNullOrEmpty(pc.UserName) ? "" : pc.UserName;   //pc.UserName;
            param[3].Value = string.IsNullOrEmpty(pc.CardTypeId) ? "" : pc.CardTypeId; //pc.CardTypeId;
            param[4].Value = pc.EndTime1;
            param[5].Value = pc.EndTime2;
            param[6].Value = string.IsNullOrEmpty(pc.OpType) ? "" : pc.OpType;// pc.OpType;
            param[7].Value = (NoBAccount ? 1 : 0);
            param[8].Value = pc.OnlyShowHideRecord;
            param[9].Value = pc.Export;
            param[10].Value = pc.PageSize;
            param[11].Value = pc.PageIndex;
            param[12].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[13].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_IssuedOpCard", param);
             
        }
        #endregion

        #region 车辆操作报表查询
        public YardPagedResult<TbrIssuedOpCard> GetTbrIssuedOpCard(TbrIssuedOpCardInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrIssuedOpCard> result = new YardPagedResult<TbrIssuedOpCard>(); 
            DataSet ds = GetTbrIssuedOpCardDB(pc, NoBAccount);
            if (ds.Tables.Count == 2)
            {
                List<TbrIssuedOpCard> li = DataTableExtend.ToDataList<TbrIssuedOpCard>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 车辆操作报表导出
        public List<TbrIssuedOpCard> ExportTbrIssuedOpCard(TbrIssuedOpCardInput pc, bool NoBAccount)
        {
            List<TbrIssuedOpCard> result = new List<TbrIssuedOpCard>(); 
            DataSet ds = GetTbrIssuedOpCardDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrIssuedOpCard>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 车辆发行报表

        #region 车辆发行数据
        public DataSet GetTbrIssuedDB(TbrIssuedInput pc, bool NoBAccount)
        {
             
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar), //车牌号码
                new SqlParameter("@UserName", System.Data.SqlDbType.NVarChar), //车主姓名
                new SqlParameter("@CardTypeId", System.Data.SqlDbType.NVarChar), //卡类编号1401这类
                new SqlParameter("@Express", System.Data.SqlDbType.NVarChar), //表达式
                new SqlParameter("@YDay", System.Data.SqlDbType.Int), //剩余天数
                new SqlParameter("@EndTime", System.Data.SqlDbType.DateTime), //操作时间
                new SqlParameter("@OverTime", System.Data.SqlDbType.Int), ///*是否过期 0否 1是 2全部*/  
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@OnlyAccount",System.Data.SqlDbType.Int),//B账查询 
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = string.IsNullOrEmpty(pc.PlateNo) ? "" : pc.PlateNo;  //pc.PlateNo;
            param[2].Value = string.IsNullOrEmpty(pc.UserName) ? "" : pc.UserName;   //pc.UserName;
            param[3].Value = string.IsNullOrEmpty(pc.CardTypeId) ? "" : pc.CardTypeId; //pc.CardTypeId;
            param[4].Value = pc.Express;
            param[5].Value = pc.YDay;
            param[6].Value = pc.EndTime;
            param[7].Value = pc.OverTime;
            param[8].Value = (NoBAccount ? 1 : 0);
            param[9].Value = pc.OnlyShowHideRecord;
            param[10].Value = pc.Export;
            param[11].Value = pc.PageSize;
            param[12].Value = pc.PageIndex;
            param[13].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[14].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_Issued", param);
             
        }
        #endregion

        #region 车辆发行查询
        public YardPagedResult<TbrIssued> GetTbrIssued(TbrIssuedInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrIssued> result = new YardPagedResult<TbrIssued>(); 
            DataSet ds = GetTbrIssuedDB(pc,NoBAccount);
            if (ds.Tables.Count == 2)
            {
                List<TbrIssued> li = DataTableExtend.ToDataList<TbrIssued>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 车辆发行导出
        public List<TbrIssued> ExportTbrIssued(TbrIssuedInput pc, bool NoBAccount)
        {
            List<TbrIssued> result = new List<TbrIssued>(); 
            DataSet ds = GetTbrIssuedDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrIssued>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 停车券明细

        #region 停车券明细数据
        public DataSet GetTbrDiscountDB(TbrDiscountInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_Id", System.Data.SqlDbType.BigInt), //场所编号
                new SqlParameter("@SaleId", System.Data.SqlDbType.BigInt), //商户号
                new SqlParameter("@CREATE_TIME1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@CREATE_TIME2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@Recv_TIME1", System.Data.SqlDbType.DateTime), //领取时间
                new SqlParameter("@Recv_TIME2", System.Data.SqlDbType.DateTime), //领取时间
                new SqlParameter("@Use_TIME1", System.Data.SqlDbType.DateTime), //使用时间
                new SqlParameter("@Use_TIME2", System.Data.SqlDbType.DateTime), //使用时间
                new SqlParameter("@Id", System.Data.SqlDbType.BigInt), //编号
                new SqlParameter("@PayStatus", System.Data.SqlDbType.NVarChar,50), //支付状态 
                new SqlParameter("@RecvStatus", System.Data.SqlDbType.NVarChar,50), //领取状态
                new SqlParameter("@UseStatus", System.Data.SqlDbType.NVarChar,50), //使用状态
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar,50), //车牌
                new SqlParameter("@HadOverTime", System.Data.SqlDbType.Bit), //过期券
                new SqlParameter("@NoBAccount",System.Data.SqlDbType.Int),//B账查询
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = pc.SaleId;
            param[2].Value = pc.CREATE_TIME1;
            param[3].Value = pc.CREATE_TIME2;

            param[4].Value = pc.Recv_TIME1;
            param[5].Value = pc.Recv_TIME2;

            param[6].Value = pc.Use_TIME1;
            param[7].Value = pc.Use_TIME2;

            param[8].Value = (pc.DisId == null ? 0 : pc.DisId);

            param[9].Value = pc.PayStatus;
            param[10].Value = pc.RecvStatus;
            param[11].Value = pc.UseStatus;

            param[12].Value = pc.PlateNo;
            param[13].Value = pc.HadOverTime;
            param[14].Value = (NoBAccount ? 1 : 0);
            param[15].Value = pc.Export;
            param[16].Value = pc.PageSize;
            param[17].Value = pc.PageIndex;
            param[18].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[19].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_Discount", param);
            
        }
        #endregion

        #region 停车券明细查询
        public YardPagedResult2<DataTable> GetTbrDiscount(TbrDiscountInput pc,bool NoBAccount)
        {
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>(); 
            DataSet ds = GetTbrDiscountDB(pc,NoBAccount);
            if (ds.Tables.Count >= 3)
            {
                //List<TbrDiscount> li = DataTableExtend.ToDataList<TbrDiscount>(ds.Tables[0]);
                DataTable t = ds.Tables[0];
                DataTable s = ds.Tables[2];
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = t;
                result.s = s;
                result.o = null;
            }
            return result;
        }
        #endregion

        #region 停车券明细导出
        public List<TbrDiscount> ExportTbrDiscount(TbrDiscountInput pc, bool NoBAccount)
        {
            List<TbrDiscount> result = new List<TbrDiscount>(); 
            DataSet ds = GetTbrDiscountDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrDiscount>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 交班统计

        #region 交班统计数据
        public DataSet GetTbrChangeClassDB(TbrChangeClassInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@LoginDate1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@LoginDate2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@LoginName", System.Data.SqlDbType.NVarChar,50), //操作员
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询  
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.LoginDate1;
            param[2].Value = pc.LoginDate2;
            param[3].Value = pc.LoginName;
            param[4].Value = (NoBAccount ? 1 : 0);
            param[5].Value = pc.Export;
            param[6].Value = pc.PageSize;
            param[7].Value = pc.PageIndex;
            param[8].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[9].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_ChangeClass", param);
             
        }
        #endregion

        #region 交班统计查询
        public YardPagedResult<TbrChangeClass> GetTbrChangeClass(TbrChangeClassInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrChangeClass> result = new YardPagedResult<TbrChangeClass>(); 
            DataSet ds = GetTbrChangeClassDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<TbrChangeClass> li = DataTableExtend.ToDataList<TbrChangeClass>(ds.Tables[0]);
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 交班统计导出
        public List<TbrChangeClass> ExportTbrChangeClass(TbrChangeClassInput pc, bool NoBAccount)
        {
            List<TbrChangeClass> result = new List<TbrChangeClass>(); 
            DataSet ds = GetTbrChangeClassDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrChangeClass>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 交班统计版本2

        #region 交班统计数据版本2
        public DataSet GetTbrChangeClass2DB(TbrChangeClassInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@LoginDate1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@LoginDate2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@LoginName", System.Data.SqlDbType.NVarChar,50), //操作员
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询  
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //导出
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };

            param[0].Value = pc.Station_No;
            param[1].Value = pc.LoginDate1;
            param[2].Value = pc.LoginDate2;
            param[3].Value = pc.LoginName;
            param[4].Value = (NoBAccount ? 1 : 0);
            param[5].Value = pc.Export;
            param[6].Value = pc.PageSize;
            param[7].Value = pc.PageIndex;
            param[8].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[9].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_ChangeClassV2", param);
             
        }
        #endregion

        #region 交班统计查询版本2
        public YardPagedResult2<DataTable> GetTbrChangeClass2(TbrChangeClassInput pc, bool NoBAccount)
        {
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>();
            DataSet ds = GetTbrChangeClass2DB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                DataTable li = ds.Tables[0];
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count;
                result.t = li;
                result.s = null;
                result.o = ds.Tables[1];
            }
            return result;
        }
        #endregion

        #region 交班统计导出版本2
        public DataTable ExportTbrChangeClass2(TbrChangeClassInput pc, bool NoBAccount)
        {
            DataTable result = new DataTable(); 
            DataSet ds = GetTbrChangeClass2DB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = ds.Tables[0];
            }
            return result;
        }
        #endregion

        #endregion

        #region 收费统计

        #region 收费统计数据
        public DataSet GetTbrStaticsDB(TbrStaticsInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@OutTime1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@OutTime2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@StaticType", System.Data.SqlDbType.NVarChar), //生成时间
                 
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.OutTime1;
            param[2].Value = pc.OutTime2;
            param[3].Value = pc.StaticType;

            param[4].Value = (NoBAccount ? 1 : 0);
            param[5].Value = pc.Export;
            param[6].Value = pc.PageSize;
            param[7].Value = pc.PageIndex;
            param[8].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[9].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_Statics", param);
             
        }
        #endregion

        #region 收费统计查询
        public YardPagedResult<TbrStatics> GetTbrStatics(TbrStaticsInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrStatics> result = new YardPagedResult<TbrStatics>(); 
            DataSet ds = GetTbrStaticsDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<TbrStatics> li = DataTableExtend.ToDataList<TbrStatics>(ds.Tables[0]);
                List<TbrStatics> statics = DataTableExtend.ToDataList<TbrStatics>(ds.Tables[1]);
                foreach (TbrStatics item in statics)
                {
                    li.Add(item);
                }
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 收费统计导出
        public List<TbrStatics> ExportTbrStatics(TbrStaticsInput pc, bool NoBAccount)
        {
            List<TbrStatics> result = new List<TbrStatics>(); 
            DataSet ds = GetTbrStaticsDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<TbrStatics> li = DataTableExtend.ToDataList<TbrStatics>(ds.Tables[0]);
                List<TbrStatics> statics = DataTableExtend.ToDataList<TbrStatics>(ds.Tables[1]);
                foreach (TbrStatics item in statics)
                {
                    li.Add(item);
                }
                return li;
                //result = DataTableExtend.ToDataList<TbrStatics>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 收费统计版本2

        #region 收费统计数据版本2
        public DataSet GetTbrStatics2DB(TbrStaticsInput pc, bool NoBAccount)
        {
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@OutTime1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@OutTime2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@StaticType", System.Data.SqlDbType.NVarChar), //生成时间
                 
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.OutTime1;
            param[2].Value = pc.OutTime2;
            param[3].Value = pc.StaticType;
            param[4].Value = (NoBAccount ? 1 : 0);
            param[5].Value = pc.Export;
            param[6].Value = pc.PageSize;
            param[7].Value = pc.PageIndex;
            param[8].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[9].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_StaticsV2", param);
             
        }
        #endregion

        #region 收费统计查询版本2
        public YardPagedResult2<DataTable> GetTbrStatics2(TbrStaticsInput pc, bool NoBAccount)
        {
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>(); 
            DataSet ds = GetTbrStatics2DB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {

                DataTable li = new DataTable();
                li = ds.Tables[0];
                li.ImportRow(ds.Tables[1].Rows[0]);
                //li.Rows.Add(ds.Tables[1].Rows[0]);

                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
                result.s = null;
                result.o = null;
            }
            return result;
        }
        #endregion

        #region 收费统计导出版本2
        public DataTable ExportTbrStatics2(TbrStaticsInput pc, bool NoBAccount)
        {
            DataTable result = new DataTable(); 
            DataSet ds = GetTbrStatics2DB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                DataTable li = new DataTable();
                li = ds.Tables[0];
                li.ImportRow(ds.Tables[1].Rows[0]);
                //li.Rows.Add(ds.Tables[1].Rows[0]);
                return li;
            }
            return result;
        }
        #endregion

        #endregion

        #region 收费统计版本3

        #region 收费统计数据版本3
        public DataSet GetTbrStatics3DB(TbrStaticsInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@OutTime1", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@OutTime2", System.Data.SqlDbType.DateTime), //生成时间
                new SqlParameter("@StaticType", System.Data.SqlDbType.NVarChar), //生成时间
                 
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.OutTime1;
            param[2].Value = pc.OutTime2;
            param[3].Value = pc.StaticType;
            param[4].Value = (NoBAccount ? 1 : 0);
            param[5].Value = pc.Export;
            param[6].Value = pc.PageSize;
            param[7].Value = pc.PageIndex;
            param[8].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[9].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_StaticsV3", param);
             
        }
        #endregion

        #region 收费统计查询版本3
        public YardPagedResult2<DataTable> GetTbrStatics3(TbrStaticsInput pc, bool NoBAccount)
        {
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>();
             
            DataSet ds = GetTbrStatics3DB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {

                DataTable li = new DataTable();
                li = ds.Tables[0];
                li.ImportRow(ds.Tables[1].Rows[0]);
                //li.Rows.Add(ds.Tables[1].Rows[0]);

                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
                result.s = null;
                result.o = null;
            }
            return result;
        }
        #endregion

        #region 收费统计导出版本3
        public DataTable ExportTbrStatics3(TbrStaticsInput pc, bool NoBAccount)
        {
             
            DataSet ds = GetTbrStatics3DB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            { 
                return ds.Tables[0];
            }
            return null;
        }
        #endregion

        #endregion

        #region 在线支付

        #region 在线支付数据
        public DataSet GetTbrOnlinePayDB(TbrOnlinePayInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@Station_No", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@Pay_TIME1", System.Data.SqlDbType.DateTime), //支付时间
                new SqlParameter("@Pay_TIME2", System.Data.SqlDbType.DateTime), //支付时间
                new SqlParameter("@source", System.Data.SqlDbType.Int), //来源
                new SqlParameter("@out_trade_no", System.Data.SqlDbType.NVarChar), //订单号码
                new SqlParameter("@trade_no", System.Data.SqlDbType.NVarChar), //交易订单
                new SqlParameter("@PlateNo", System.Data.SqlDbType.NVarChar), //车牌号码
                 
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询  
                new SqlParameter("@Export", System.Data.SqlDbType.NVarChar,50), //通道设备号
                new SqlParameter("@PageSize", System.Data.SqlDbType.Int), //页大小
                new SqlParameter("@PageIndex", System.Data.SqlDbType.Int), //页码
                new SqlParameter("@OrderBy", System.Data.SqlDbType.NVarChar,50), //排序字段
                new SqlParameter("@Desc", System.Data.SqlDbType.NVarChar,50)//

            };
            param[0].Value = pc.Station_No;
            param[1].Value = pc.Pay_TIME1;
            param[2].Value = pc.Pay_TIME2;
            param[3].Value = pc.source;
            param[4].Value = pc.out_trade_no;
            param[5].Value = pc.trade_no;
            param[6].Value = pc.PlateNo;
            param[7].Value = (NoBAccount ? 1 : 0);
            param[8].Value = pc.Export;
            param[9].Value = pc.PageSize;
            param[10].Value = pc.PageIndex;
            param[11].Value = string.IsNullOrEmpty(pc.OrderBy) ? "" : pc.OrderBy;  //pc.OrderBy;
            param[12].Value = string.IsNullOrEmpty(pc.Desc) ? "" : pc.Desc;  //pc.Desc;


           return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_OnlinePay", param);
             
        }
        #endregion

        #region 在线支付查询
        public YardPagedResult<TbrOnlinePay> GetTbrOnlinePay(TbrOnlinePayInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrOnlinePay> result = new YardPagedResult<TbrOnlinePay>(); 
            DataSet ds = GetTbrOnlinePayDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<TbrOnlinePay> li = DataTableExtend.ToDataList<TbrOnlinePay>(ds.Tables[0]);
                result.PageCount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                result.TotalCount = Convert.ToInt32(ds.Tables[1].Rows[0][1]);
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 在线支付导出
        public List<TbrOnlinePay> ExportTbrOnlinePay(TbrOnlinePayInput pc, bool NoBAccount)
        {
            List<TbrOnlinePay> result = new List<TbrOnlinePay>(); 
            DataSet ds = GetTbrOnlinePayDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrOnlinePay>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 开票结果

        #region 开票结果数据
        public bool DeleteInvoice(List<int> delkeys)
        {
            try
            { 
                foreach(int delkey in delkeys)
                {
                    string strSql = $@"DELETE FROM  tV_INVOICE WHERE RecordId={delkey} AND returnCode<>'0000'";
                    SqlHelper.ExecuteNonQuery(GetCon(), CommandType.Text, strSql);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public DataSet GetTbrInvoiceDB(TbrInvoiceInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@StationId", System.Data.SqlDbType.Int), //场所编号 
                new SqlParameter("@DDRQ1", System.Data.SqlDbType.DateTime), //支付时间
                new SqlParameter("@DDRQ2", System.Data.SqlDbType.DateTime), //支付时间 
                new SqlParameter("@GHFMC", System.Data.SqlDbType.NVarChar), //订单号码
                new SqlParameter("@XMMC", System.Data.SqlDbType.NVarChar), //交易订单 
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询   

            };
            param[0].Value = pc.Station_Id;
            param[1].Value = pc.DDRQ1;
            param[2].Value = pc.DDRQ2;
            param[3].Value = pc.GHFMC;
            param[4].Value = pc.XMMC;
            param[5].Value = (NoBAccount ? 1 : 0);

            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_GetHadInvoiceList", param);
             
        }
        #endregion

        #region 开票结果查询
        public YardPagedResult<TbrInvoice> GetTbrInvoice(TbrInvoiceInput pc, bool NoBAccount)
        {
            YardPagedResult<TbrInvoice> result = new YardPagedResult<TbrInvoice>(); 
            DataSet ds = GetTbrInvoiceDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<TbrInvoice> li = DataTableExtend.ToDataList<TbrInvoice>(ds.Tables[0]);
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 删除未开票成功的记录行
        public bool DeleteInvoiceRecord(List<int> delkeys)
        { 
            return DeleteInvoice(delkeys); 
        }
        #endregion

        #region 开票结果导出
        public List<TbrInvoice> ExportTbrInvoice(TbrInvoiceInput pc, bool NoBAccount)
        {
            List<TbrInvoice> result = new List<TbrInvoice>(); 
            DataSet ds = GetTbrInvoiceDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<TbrInvoice>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 路政对账单

        #region 路政对账单数据
        public DataSet GetrRoadPayResultsDB(rRoadPayResultsInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@StationId", System.Data.SqlDbType.BigInt), //场所ID 
                new SqlParameter("@StationNo", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@B", System.Data.SqlDbType.DateTime), //开始日期
                new SqlParameter("@E", System.Data.SqlDbType.DateTime), //截止日期
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询   

            };
            param[0].Value = pc.StationId;
            param[1].Value = pc.StationNo;
            param[2].Value = pc.B;
            param[3].Value = pc.E;
            param[4].Value = (NoBAccount ? 1 : 0);

            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_RoadPayResults", param);
             
        }
        #endregion

        #region 路政对账单查询
        public YardPagedResult<rRoadPayResults> GetrRoadPayResults(rRoadPayResultsInput pc, bool NoBAccount)
        {
            YardPagedResult<rRoadPayResults> result = new YardPagedResult<rRoadPayResults>(); 
            DataSet ds = GetrRoadPayResultsDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<rRoadPayResults> li = DataTableExtend.ToDataList<rRoadPayResults>(ds.Tables[0]);
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 路政对账单导出
        public List<rRoadPayResults> ExportrRoadPayResults(rRoadPayResultsInput pc, bool NoBAccount)
        {
            List<rRoadPayResults> result = new List<rRoadPayResults>(); 
            DataSet ds = GetrRoadPayResultsDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<rRoadPayResults>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 路政缴费凭证

        #region 路政缴费凭证数据
        public DataSet GetrRoadbillInfosDB(rRoadbillInfosInput pc, bool NoBAccount)
        {
            YardPagedResult<rRoadbillInfos> result = new YardPagedResult<rRoadbillInfos>();
            SqlParameter[] param =
            {
                new SqlParameter("@StationId", System.Data.SqlDbType.BigInt), //场所ID 
                new SqlParameter("@StationNo", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@B", System.Data.SqlDbType.DateTime), //开始日期
                new SqlParameter("@E", System.Data.SqlDbType.DateTime), //截止日期  
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询 

            };
            param[0].Value = pc.StationId;
            param[1].Value = pc.StationNo;
            param[2].Value = pc.B;
            param[3].Value = pc.E;
            param[4].Value = (NoBAccount ? 1 : 0);


           return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_RoadbillInfos", param);
             
        }
        #endregion

        #region  路政缴费凭证查询
        public YardPagedResult<rRoadbillInfos> GetrRoadbillInfos(rRoadbillInfosInput pc, bool NoBAccount)
        {
            YardPagedResult<rRoadbillInfos> result = new YardPagedResult<rRoadbillInfos>(); 
            DataSet ds = GetrRoadbillInfosDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<rRoadbillInfos> li = DataTableExtend.ToDataList<rRoadbillInfos>(ds.Tables[0]);
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 路政缴费凭证导出
        public List<rRoadbillInfos> ExportrRoadbillInfos(rRoadbillInfosInput pc, bool NoBAccount)
        {
            List<rRoadbillInfos> result = new List<rRoadbillInfos>(); 
            DataSet ds = GetrRoadbillInfosDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<rRoadbillInfos>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 路政错峰停车

        #region 路政错峰停车数据
        public DataSet GetrRoadStaggerDB(rRoadStaggerInput pc, bool NoBAccount)
        { 
            SqlParameter[] param =
            {
                new SqlParameter("@StationId", System.Data.SqlDbType.BigInt), //场所ID 
                new SqlParameter("@StationNo", System.Data.SqlDbType.VarChar), //场所编号
                new SqlParameter("@B", System.Data.SqlDbType.DateTime), //开始日期
                new SqlParameter("@E", System.Data.SqlDbType.DateTime), //截止日期  
                new SqlParameter("@NoBAccount", System.Data.SqlDbType.Int), //B账查询 

            };
            param[0].Value = pc.StationId;
            param[1].Value = pc.StationNo;
            param[2].Value = pc.B;
            param[3].Value = pc.E;
            param[4].Value = (NoBAccount ? 1 : 0);


            return SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_RoadStagger", param);
             
        }
        #endregion

        #region 路政错峰停车查询
        public YardPagedResult<rRoadStagger> GetrRoadStagger(rRoadStaggerInput pc, bool NoBAccount)
        {
            YardPagedResult<rRoadStagger> result = new YardPagedResult<rRoadStagger>();
             
            DataSet ds = GetrRoadStaggerDB(pc,NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                List<rRoadStagger> li = DataTableExtend.ToDataList<rRoadStagger>(ds.Tables[0]);
                result.PageCount = 1;
                result.TotalCount = ds.Tables[0].Rows.Count + 1;
                result.t = li;
            }
            return result;
        }
        #endregion

        #region 路政错峰停车导出
        public List<rRoadStagger> ExportrRoadStagger(rRoadStaggerInput pc, bool NoBAccount)
        {
            List<rRoadStagger> result = new List<rRoadStagger>(); 
            DataSet ds = GetrRoadStaggerDB(pc, NoBAccount);
            if (ds.Tables.Count >= 1)
            {
                result = DataTableExtend.ToDataList<rRoadStagger>(ds.Tables[0]);
            }
            return result;
        }
        #endregion

        #endregion

        #region 车流统计

        #region 车流统计数据
        public DataTable GetTbrStatisticsCLDB(TbrStaticsCLInput pc)
        {
            DateTime B = Convert.ToDateTime(pc.Month + "-01");
            DateTime E = Convert.ToDateTime(pc.Month + "-01").AddMonths(1).AddSeconds(-1);
            int Year = Convert.ToDateTime(pc.Month + "-01").Year; 
            SqlParameter[] param =
            {
                new SqlParameter("@StationNo", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@B", System.Data.SqlDbType.DateTime), //起始日期
                new SqlParameter("@E", System.Data.SqlDbType.DateTime), //截止日期
                new SqlParameter("@G", System.Data.SqlDbType.Bit), //类型  

            };
            SqlParameter[] param2 =
            {
                new SqlParameter("@StationNo", System.Data.SqlDbType.NVarChar), //场所编号 
                new SqlParameter("@Year", System.Data.SqlDbType.Int), //类型  

            };
            param[0].Value = pc.Station_No;
            param[1].Value = B;
            param[2].Value = E;
            param[3].Value = false;
            param2[0].Value = pc.Station_No;
            param2[1].Value = Year;

            DataTable db = null;
            if (pc.RType == 1)
            {
                db = SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_reportStatisticsCL_1", param).Tables[0];
            }
            else if (pc.RType == 2)
            {
                db = SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_reportStatisticsCL_3", param).Tables[0];
            }
            else if (pc.RType == 3)
            {
                db = SqlHelper.ExecuteDataset(GetCon(), CommandType.StoredProcedure, "r_reportStatisticsCL_4", param2).Tables[0];
            }

             
            return db;
        }
        #endregion

        #region 车流统计查询
        public YardPagedResult2<DataTable> GetTbrStatisticsCL(TbrStaticsCLInput pc)
        { 
            YardPagedResult2<DataTable> result = new YardPagedResult2<DataTable>();
             

            result.PageCount = 1;
            result.TotalCount = 1;
            result.t = GetTbrStatisticsCLDB(pc);
            result.s = null;
            result.o = null;

            return result;
        }
        #endregion

        #region 车流统计导出
        public DataTable ExportTbrStatisticsCL(TbrStaticsCLInput pc)
        {  
            return GetTbrStatisticsCLDB(pc); ;
        }
        #endregion
        #endregion

        #endregion

        #region 获取当前租户下所有场所
        public List<TbStation> GetAllStationByTenantID(int TenantID)
        {
            List<TbStation> spAll = new List<TbStation>();
            string strSql = string.Format("SELECT Id,Station_Id,Station_No,Station_Type,Station_Name FROM "
                + " dbo.Tb_Station Where IsDeleted=0 AND TenantId={0}", TenantID);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbStation>(dt);
            }
            return spAll;
        }
        #endregion

        #region 获取当前场所下的所有商户
        public List<TbSale> GetAllSalesByStationID(long StationId)
        {
            List<TbSale> spAll = new List<TbSale>();
            string strSql = string.Format("SELECT Id,[Sale_No],[Sale_Name],[Sale_FullName] FROM dbo.Tb_Sales Where IsDeleted=0 AND [Sale_Stop]=0 AND Station_ID={0}", StationId);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                spAll = DataTableExtend.ToDataList<TbSale>(dt);
            }
            return spAll;
        }
        #endregion

        #region 获取当前场所下所有免单券类型
        public List<string> GetAllBillNameByStationID(long StationId)
        {
            List<string> spAll = new List<string>();
            string strSql = string.Format("DECLARE @Station_No varchar(20) "
                            + " SELECT @Station_No = Station_No FROM Tb_Station WHERE Station_ID = {0} "
                            + " EXEC('SELECT tFree_Name FROM  tY_Free_' + @Station_No + N' GROUP BY tFree_Name order by tFree_Name') ", StationId);
            DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    spAll.Add(row["tFree_Name"].ToString().Trim());
                }
            }
            return spAll;
        }
        #endregion

        #region 数字人民币批量扣款
        //数字人民币批量扣款--订单列表
        public List<tVDIGITALPAYMAIN> GetDIGITALPAY(List<long> StationId, DateTime? bTime, DateTime? eTime, bool? isDelete)
        {
            try
            {
                string stids = string.Join(',', StationId);
                List<tVDIGITALPAYMAIN> spAll = new List<tVDIGITALPAYMAIN>();
                string strSql = $@"SELECT * FROM vV_DIGITALPAY 
                                   WHERE [Station_Id] IN ({stids}) AND [UpTime]>='{((bTime ?? (new DateTime(1900, 1, 1))).ToString("yyyy-MM-dd"))}'
                                   AND [UpTime]<='{((eTime ?? (new DateTime(2900, 1, 1))).ToString("yyyy-MM-dd") + " 23:59:59")}'
                                   AND [IsDeleted]={((isDelete ?? false) ? "1" : "0")}  ORDER BY UpTime DESC ";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    spAll = DataTableExtend.ToDataList<tVDIGITALPAYMAIN>(dt);
                }
                return spAll;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        public List<tVDIGITALPAYIds> GetDIGITALPAY(long StationId, string billNo)
        {
            try
            {
                string stids = string.Join(',', StationId);
                List<tVDIGITALPAYIds> spAll = new List<tVDIGITALPAYIds>();
                string strSql = $@"SELECT Id FROM tV_DIGITALPAY 
                                   WHERE [Station_Id]={StationId} AND BillNo='{billNo}'  ";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    spAll = DataTableExtend.ToDataList<tVDIGITALPAYIds>(dt);
                }
                return spAll;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

        #region 数字人民币扣款获取单号
        //获取单号
        public string GetBillNo(long stationId)
        {
            try
            {
                DateTime bTime = DateTime.Now;
                string strSql = $@"SELECT ISNULL(MAX(BillNo),{bTime.ToString("yyyyMM")}000)+1  BillNo FROM tV_DIGITALPAY WHERE Station_Id={stationId} AND BillNo LIKE '{bTime.ToString("yyyyMM")}%' ";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    return dt.Rows[0][0].ToString();
                }
                return "";
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        #endregion

        #region 获取交易信息
        public bool getClientInfor(string billNo, long stationId, int isDigity, ref string md5Key, ref string stationNo, ref string stationName, ref long clientId, ref string clientNo, ref string clientName)
        {
            try
            {
                string strSql = $@"SELECT A.Station_ID,A.Id,A.Client_ID,A.Client_Name,B.Station_No,B.Station_Name,B.Station_MD5Key 
                                    FROM [dbo].[Tb_ClientRegister] A LEFT JOIN Tb_Station B ON A.Station_ID=B.Station_ID
                                    WHERE A.Station_ID={stationId} AND A.Client_Stop=0 AND A.IsDeleted=0 AND B.Station_Stop=0 AND B.IsDeleted=0
                                    AND A.Client_ID='{(isDigity == 1 ? "CCBDTPAY" : "CCBWGPAY")}'";
                DataTable db = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (db !=null && db.Rows.Count > 0)
                {
                    md5Key = db.Rows[0]["Station_MD5Key"].ToString();
                    stationNo = db.Rows[0]["Station_No"].ToString();
                    stationName = db.Rows[0]["Station_Name"].ToString();
                    clientId = Convert.ToInt64(db.Rows[0]["Id"]);
                    clientNo = db.Rows[0]["Client_ID"].ToString();
                    clientName = db.Rows[0]["Client_Name"].ToString();
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                AiLogger.Instance.Error("批量扣款异常-->获取交易信息异常-->" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 获取数字人民币扣款明细
        public async Task<List<TvDigitalPayDto>> GetBillInfo(long stationId, string billNo, bool ischeck)
        {
            List<TvDigitalPayDto> spAll = new List<TvDigitalPayDto>();
            try
            { 
                
                string strSql = $@"SELECT * FROM tV_DIGITALPAY 
                                   WHERE [Station_Id]={stationId} AND BillNo='{billNo}' AND [IsDeleted]=0 ";
                if (ischeck)
                {
                    strSql = strSql + " AND ISNULL(CheckStatus,N'')=N'同意'";
                }
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    spAll = DataTableExtend.ToDataList<TvDigitalPayDto>(dt);
                }
                return spAll;
            }
            catch (Exception ex)
            {
                return spAll;
            }
        }
        #endregion

        #region 数字人民币扣款导入
        //导入月卡数据
        public async Task<Dictionary<string, string>> BatchLoadDigitalPay(int isDigityPay, string name, bool isCheckerr, bool isEdit, string fileName, string billno, string title, long stationId, int TenantId, int opUserId, string opUserName, string opUserTureName)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            result.Add("retype", "1");
            if (isCheckerr)
            {
                result.Add("revalue", name);
            }
            else
            {
                result.Add("revalue", "导入数据成功");
            }
            AiLogger.Instance.WriteLog("准备导入-->" + result.ToJson(), "扣款单上传");
            try
            {
                //string strSql2 = $@"SELECT ISNULL(Max([UpTime]),dateadd(day,-9,getdate())) UpTime FROM [dbo].[tV_DIGITALPAY] WHERE [CheckStatus] IS NULL ";
                //DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql2).Tables[0];
                //DateTime lastupTime = DateTime.Now.AddDays(-9);
                //if (dt == null || dt.Rows.Count <= 0)
                //{
                //    lastupTime = Convert.ToDateTime(dt.Rows[0][0]);
                //}
                string strSql2 = $@"SELECT 0 FROM [dbo].[tV_DIGITALPAY] WHERE [Station_Id]={stationId} ";
                DataTable dtt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql2).Tables[0];
                if (!isEdit && dtt != null && dtt.Rows.Count>0)
                {
                    result.Clear();
                    result.Add("retype", "-1");
                    result.Add("revalue", "当前单号已经存在");
                    AiLogger.Instance.WriteLog("单号存在-->" + result.ToJson(), "扣款单上传");
                    return result;
                }
                DateTime upTime = DateTime.Now;

                //TimeSpan span = upTime - lastupTime;
                 

                var errorList = new List<string>();
                string fullPath = fileName;

                IWorkbook wk = null;
                string extension = System.IO.Path.GetExtension(fullPath);
               


                FileStream fs = new FileStream(fullPath, FileMode.Open);
                if (extension.Equals(".xls"))
                {
                    //把xls文件中的数据写入wk中
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //把xlsx文件中的数据写入wk中
                    wk = new XSSFWorkbook(fs);
                }



                fs.Close();
                string err = "";

                //读取当前表数据
                ISheet sheet = wk.GetSheetAt(0);
                IRow row = sheet.GetRow(0);  //读取当前行数据
                string strJsonArrary = "";
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    try
                    {
                        row = sheet.GetRow(i);  //读取当前行数据
                        if (row != null && row.GetCell(0) != null && row.GetCell(0).ToString() != "" && row.GetCell(0).ToString() != "{}")
                        {

                            string plateNo = "";
                            int plateColor = 0;
                            string userName = "";
                            DateTime? inTime = null;
                            DateTime? outTime = null;
                            string inGate = "";
                            string outGate = "";
                            decimal amount = 0;

                            //LastCellNum 是当前行的总列数
                            for (int j = 0; j < 8; j++)
                            {
                                //读取该行的第j列数据
                                if (j == 0 || j == 3 || j == 6 || j == 7)
                                {
                                    if (j == 0)
                                    {
                                        plateNo = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                    }
                                    else if (j == 3)
                                    {
                                        userName = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                    }
                                    else if (j == 6)
                                    {
                                        inGate = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                    }
                                    else if (j == 7)
                                    {
                                        outGate = row.GetCell(j) == null ? "" : row.GetCell(j).ToString().Trim();
                                    }
                                }
                                else if (j == 1)
                                {
                                    string carcolor = row.GetCell(j) == null ? "未知" : row.GetCell(j).ToString().Trim();
                                    switch (carcolor)
                                    {
                                        case "蓝色":
                                            {
                                                plateColor = 1;
                                                break;
                                            }
                                        case "黄色":
                                            {
                                                plateColor = 2;
                                                break;
                                            }
                                        case "白色":
                                            {
                                                plateColor = 3;
                                                break;
                                            }
                                        case "黑色":
                                            {
                                                plateColor = 4;
                                                break;
                                            }
                                        case "绿色":
                                            {
                                                plateColor = 5;
                                                break;
                                            }
                                        case "未知":
                                            {
                                                plateColor = 6;
                                                break;
                                            }
                                    };
                                }
                                else if (j == 2)
                                {
                                    string AmountStr = row.GetCell(j) == null ? "0" : row.GetCell(j).ToString().Trim();

                                    if (!decimal.TryParse(AmountStr, out amount))
                                    {
                                        AmountStr = row.GetCell(j).StringCellValue.ToString().Trim();
                                        if (!decimal.TryParse(AmountStr, out amount))
                                        {
                                            amount = 0;
                                        }
                                    }

                                }
                                else if (j == 4)
                                {
                                    string TimeStr = row.GetCell(j).ToString().Trim().Replace('/', '-');
                                    DateTime ii = DateTime.Now;
                                    if (!DateTime.TryParse(TimeStr, out ii))
                                    {
                                        TimeStr = row.GetCell(j).DateCellValue.ToString();
                                        if (DateTime.TryParse(TimeStr, out ii))
                                        {
                                            inTime = ii; 
                                        }
                                    }
                                    else
                                    {
                                        inTime = ii;
                                    }
                                }
                                else if (j == 5)
                                {
                                    string TimeStr = row.GetCell(j).ToString().Trim().Replace('/', '-');
                                    DateTime ii = DateTime.Now;
                                    if (!DateTime.TryParse(TimeStr, out ii))
                                    {
                                        TimeStr = row.GetCell(j).DateCellValue.ToString();
                                        if (DateTime.TryParse(TimeStr, out ii))
                                        {
                                            outTime = ii;
                                        }
                                    }
                                    else
                                    {
                                        outTime = ii;
                                    }
                                }
                                 
                            }
                            if (plateNo == "" || !isPlateLicense(plateNo))
                            {
                                err = err + i.ToString() + $@"({plateNo}车牌错误),";
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}车牌错误),", "扣款单上传");
                            }
                            else if (amount <= 0)
                            {
                                err = err + i.ToString() + $@"({amount}金额错误),";
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({amount}金额错误),", "扣款单上传");
                            }
                            else if (inTime == null)
                            {
                                err = err + i.ToString() + $@"({plateNo}进场时间不允许为空),";
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}进场时间不允许为空),", "扣款单上传");
                            }
                            else if (inTime == null)
                            {
                                err = err + i.ToString() + $@"({plateNo}出场时间不允许为空),";
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}出场时间不允许为空),", "扣款单上传");
                            }
                            else if (string.IsNullOrEmpty(inGate))
                            {
                                err = err + i.ToString() + $@"({plateNo}进场通道不允许为空),"; 
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}进场通道不允许为空),", "扣款单上传");
                            }
                            else if (string.IsNullOrEmpty(outGate))
                            {
                                err = err + i.ToString() + $@"({plateNo}出场通道不允许为空),";
                                AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}出场通道不允许为空),", "扣款单上传");
                            }
                            else
                            {
                                //未扣款的车牌只能上传一次
                                string strSql = $@"SELECT 0 FROM [dbo].[tV_DIGITALPAY] WHERE [plateNo]=N'{plateNo}' AND (CASE WHEN {isDigityPay}=1 THEN [digitalStatus] ELSE [entityStatus] END IS NULL) 
                                                   AND (CASE WHEN {isDigityPay}=1 THEN ISNULL([CheckStatus],N'') ELSE ISNULL([CheckStatus],N'') END =N'' OR CASE WHEN {isDigityPay}=1 THEN ISNULL([CheckStatus],N'') ELSE ISNULL([CheckStatus],N'') END=N'同意') AND [IsDeleted]=0 AND isDigityPay={isDigityPay}";
                                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                                if (dt == null || dt.Rows.Count <= 0)
                                {
                                    if (!isCheckerr)
                                    {
                                        strSql = $@"SELECT Station_Name,Station_No FROM tb_Station  WHERE Station_ID={stationId}";
                                        DataTable dd = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                                        string StationName = dd.Rows[0][0].ToString();
                                        string StationNo = dd.Rows[0][1].ToString();
                                        int recordId = insertOutYardrecord(plateNo, plateColor, userName, inTime ?? DateTime.Now, outTime ?? DateTime.Now, inGate, outGate, opUserId, opUserTureName, StationNo);
                                        if (recordId > 0)
                                        {
                                            strSql = $@" 
                                                   INSERT INTO [dbo].[tV_DIGITALPAY]
                                                   ([Station_Id]
                                                   ,[Station_Name]
                                                   ,[BillNo]
                                                   ,[Title]
                                                   ,[Memo]
                                                   ,[UpuserId]
                                                   ,[UpuserName]
                                                   ,[UpuserTrueName]
                                                   ,[UpTime]
                                                   ,[plateNo]
                                                   ,[plateColor]
                                                   ,[owner]
                                                   ,[inTime]
                                                   ,[outTime]
                                                   ,[inGate]
                                                   ,[outGate]
                                                   ,[isDigityPay]
                                                   ,[Amout]
                                                   ,[TenantId]
                                                   ,[CreationTime]
                                                   ,[CreatorUserId]
                                                   ,[LastModifierUserId]
                                                   ,[LastModificationTime]
                                                   ,[IsDeleted]
                                                   ,[DeleterUserId]
                                                   ,[DeletionTime]
                                                   ,[RecordId])
                                             VALUES
                                                   ({stationId}
                                                   ,N'{StationName}'
                                                   ,'{billno}'
                                                   ,N'{title}'
                                                   ,N''
                                                   ,{opUserId}
                                                   ,'{opUserName}'
                                                   ,N'{opUserTureName}'
                                                   ,{("'" + upTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")}
                                                   ,N'{plateNo}'
                                                   ,{plateColor}
                                                   ,N'{userName}'
                                                   ,{(inTime == null ? "'null'" : ("'" + (inTime ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss") + "'"))}
                                                   ,{(outTime == null ? "'null'" : ("'" + (outTime ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss") + "'"))}
                                                   ,N'{inGate}'
                                                   ,N'{outGate}'
                                                   ,{isDigityPay}
                                                   ,{amount}
                                                   ,{TenantId}
                                                   ,getdate()
                                                   ,{opUserId}
                                                   ,null
                                                   ,null
                                                   ,0
                                                   ,null
                                                   ,null
                                                   ,{recordId})";
                                            if (SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) <= 0)
                                            {
                                                err = err + i.ToString() + $@"(导入错误),";
                                                AiLogger.Instance.WriteLog(i.ToString() + $@"(导入错误),", "扣款单上传");
                                            }
                                            else
                                            {
                                                AiLogger.Instance.WriteLog(strSql, "扣款单上传");
                                            }
                                        }
                                        else
                                        {
                                            err = err + i.ToString() + $@"(保存进出记录失败),";
                                            AiLogger.Instance.WriteLog(i.ToString() + $@"(保存进出记录失败),", "扣款单上传");
                                        }
                                    }
                                    else
                                    {
                                        AiLogger.Instance.WriteLog(i.ToString() + $@"(仅检查错误),", "扣款单上传");
                                    }
                                }
                                else
                                {
                                    err = err + i.ToString() + $@"({plateNo}重复行),";
                                    AiLogger.Instance.WriteLog(i.ToString() + $@"({plateNo}重复行),", "扣款单上传");
                                }
                            }
                             
                        }
                    }
                    catch (Exception exx)
                    {
                        LogHelper.Logger.Error(exx.Message);
                        err = err + i.ToString() + ",";
                        AiLogger.Instance.WriteLog("异常-->" + err, "扣款单上传");
                    }
                }
                if (err != "")
                {
                    result.Clear();
                    result.Add("retype", "-1");
                    result.Add("revalue", "错误的行【" + err + "】");
                    AiLogger.Instance.WriteLog("错误的行-->【" + err + "】", "扣款单上传");
                }
            }
            catch (Exception e)
            {
                result.Clear();
                result.Add("retype", "-1");
                result.Add("revalue", e.Message);
                AiLogger.Instance.WriteLog("异常-->【" + result.ToJson() + "】", "扣款单上传");
            }
            return result;
        }
        #endregion

        #region 数字人民币扣款审核单据
        public async Task<Dictionary<string, string>> CheckDigitalPayByBillNo(long stationId, string billNo, string checkStatus, string checkMemo, long checkuser, string checkuserName, string checkuserTrueName)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            result.Add("retype", "1"); 
            result.Add("revalue", "审核单据成功");

            try
            {
                string strSql = $@"UPDATE tV_DIGITALPAY SET [CheckuserId]={checkuser}
                                   ,[CheckuserName]='{checkuserName}'
                                   ,[CheckuserTrueName]=N'{checkuserTrueName}'
                                   ,[CheckTime]=getdate()
                                   ,[CheckStatus]=N'{checkStatus}'
                                   ,[CheckMemo]=N'{checkMemo}' WHERE [Station_Id]={stationId} AND [BillNo]='{billNo}' AND ([entityStatus] IS NULL AND [digitalStatus] IS NULL)";
                SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql);

                result.Clear();
                result.Add("retype", "1");
                result.Add("revalue", "审核单据成功");

            }
            catch (Exception ex)
            {
                result.Clear();
                result.Add("retype", "-1");
                result.Add("revalue", ex.Message);
            }
            return result;
        }
        #endregion

        #region 更新审核密码
        public string getAudUser(int type,long stationId)
        {
            try
            {
                string strSql = $" SELECT b.PhoneNumber FROM [Tb_DigitalPaychk] a left join abp.Users b on a.[aud_0]=b.Id WHERE A.Station_Id={stationId}";
                if (type == 2)
                {
                    strSql = $" SELECT b.PhoneNumber FROM [Tb_DigitalPaychk] a left join abp.Users b on a.[aud_1]=b.Id WHERE A.Station_Id={stationId}";
                }
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    return dt.Rows[0][0].ToString();
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public bool isAudUser(long userId)
        {
            try
            {
                string strSql = $" SELECT ISNULL([aud_0_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_0]={userId} UNION ALL SELECT ISNULL([aud_1_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_1]={userId}";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public int getAudUserType(long userId)
        {
            try
            {
                string strSql = $" SELECT 1 as AudType, ISNULL([aud_0_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_0]={userId} UNION ALL SELECT 2 as AudType, ISNULL([aud_1_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_1]={userId}";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dt.Rows.Count > 1) {
                        return 3;
                    }
                    return Convert.ToInt32(dt.Rows[0][0]);
                }
                else
                {
                    return 0;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        public int getAudPasswordType(long userId)
        {
            try
            {
                string strSql = $" SELECT ISNULL([aud_0_pswtype],1) PSW FROM [Tb_DigitalPaychk] WHERE [aud_0]={userId} UNION ALL SELECT ISNULL([aud_1_pswtype],1) PSW FROM [Tb_DigitalPaychk] WHERE [aud_1]={userId}";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    return Convert.ToInt32(dt.Rows[0]["PSW"]);
                }
                else
                {
                    return 1;
                }
            }
            catch (Exception ex)
            {
                return 1;
            }
        }
        public string getAudPassword(long userId)
        {
            try
            {
                string strSql = $" SELECT ISNULL([aud_0_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_0]={userId} UNION ALL SELECT ISNULL([aud_1_psw],'') PSW FROM [Tb_DigitalPaychk] WHERE [aud_1]={userId}";
                DataTable dt = SqlHelper.ExecuteDataset(this.GetCon(), CommandType.Text, strSql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    return dt.Rows[0]["PSW"].ToString();
                }
                else
                {
                    return "**";
                }
            }
            catch (Exception ex)
            {
                return "**";
            }
        }
        public bool isUpdateAudPassword(long userId, string password)
        {
            try
            {
                string strSql = $" UPDATE [Tb_DigitalPaychk] set [aud_0_psw]='{password}' WHERE [aud_0]={userId} UPDATE [Tb_DigitalPaychk] set [aud_1_psw]='{password}' WHERE [aud_1]={userId} ";

                return SqlHelper.ExecuteNonQuery(this.GetCon(), CommandType.Text, strSql) > 0;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region 批量数字人民扣款新增出场记录
        public int insertOutYardrecord(string plateNo, int plateColor,string owner, DateTime InTime, DateTime OutTime, string inGate, string outGate, long userId, string userTureName,string StationNo)
        {
            try
            {
                SqlParameter[] param =
                {
                new SqlParameter("@plateNo", System.Data.SqlDbType.NVarChar), // 
                new SqlParameter("@plateColor", System.Data.SqlDbType.Int), //
                new SqlParameter("@inTime", System.Data.SqlDbType.DateTime), //
                new SqlParameter("@outTime", System.Data.SqlDbType.DateTime), //
                new SqlParameter("@inGate", System.Data.SqlDbType.NVarChar), //
                new SqlParameter("@outGate", System.Data.SqlDbType.NVarChar), //
                new SqlParameter("@owner", System.Data.SqlDbType.NVarChar), //
                 
                new SqlParameter("@opuserId", System.Data.SqlDbType.Int), //  
                new SqlParameter("@opuserName", System.Data.SqlDbType.NVarChar,50), //
                new SqlParameter("@StationNo", System.Data.SqlDbType.VarChar), //
                new SqlParameter("@recordId", System.Data.SqlDbType.Int), //  
                };
                param[0].Value = plateNo;
                param[1].Value = plateColor;
                param[2].Value = InTime;
                param[3].Value = OutTime;
                param[4].Value = inGate;
                param[5].Value = outGate;
                param[6].Value = owner;
                param[7].Value = userId;
                param[8].Value = userTureName;
                param[9].Value = StationNo;
                param[10].Value = 0;
                param[10].Direction = ParameterDirection.InputOutput;



                SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "o_InsertOutYardDigity", param);
                if (Convert.ToInt32(param[10].Value) > 0)
                {
                    return Convert.ToInt32(param[10].Value);
                }
                return 0;
            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error(ex.Message);
                return 0;
            }
        }
        #endregion

        #region 批量数字人民币扣款新增交易记录
        public bool insertOutYardpay(string billNo, string plateNo, int recordId, decimal recvAmt, long userId, string userTureName, long clientId, string StationNo)
        {
            try
            {
                SqlParameter[] param =
                {
                    new SqlParameter("@recordId", System.Data.SqlDbType.Int),
                    new SqlParameter("@recvAmt", System.Data.SqlDbType.Decimal),
                    new SqlParameter("@longAmt", System.Data.SqlDbType.Decimal),
                    new SqlParameter("@opuserId", System.Data.SqlDbType.BigInt),
                    new SqlParameter("@opuserTrueName", System.Data.SqlDbType.NVarChar),
                    new SqlParameter("@clientId", System.Data.SqlDbType.BigInt),
                    new SqlParameter("@stationNo", System.Data.SqlDbType.NVarChar),
                };
                param[0].Value = recordId;
                param[1].Value = recvAmt;
                param[2].Value = recvAmt;
                param[3].Value = userId;
                param[4].Value = userTureName;
                param[5].Value = clientId;
                param[6].Value = StationNo;



                if (SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "o_InsertOutYardPay", param) > 0)
                {
                    AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付记录成功", billNo);
                    return true;
                }
                else
                {
                    AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付记录失败", billNo);
                    return false;
                }
            }
            catch (Exception ex)
            {
                AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付记录异常", billNo);
                AiLogger.Instance.Error($@"{billNo}-->{plateNo}-->" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 更新数字人民币批量扣款状态
        public bool updateDigityResult(string billNo, string plateNo, int recordId, decimal tradeAmt, string tradeStatus, string errorCode, string errorMessage, DateTime requestTime, DateTime reponseTime, DateTime tradeTime, int isDigityPay)
        {
            try
            {
                string strSql = $@"UPDATE [dbo].[tV_DIGITALPAY]
                                   SET [digitalYuan] = {tradeAmt}
                                      ,[digitalStatus] = N'{tradeStatus}'
                                      ,[digitalreturnCode] = N'{errorCode}'
                                      ,[digitalreturnMessage] = N'{errorMessage}'
                                      ,[digitalrequestTime] = @requestTime
                                      ,[digitalresponseTime] = @reponseTime
                                      ,[digitalgmtTime] = @tradeTime  WHERE Id={recordId}";
                if (isDigityPay != 1)
                {
                    strSql = $@"UPDATE [dbo].[tV_DIGITALPAY]
                                   SET [entityRMB] = {tradeAmt}
                                      ,[entityStatus] = N'{tradeStatus}'
                                      ,[entityreturnCode] = N'{errorCode}'
                                      ,[entityreturnMessage] = N'{errorMessage}'
                                      ,[entityrequestTime] = @requestTime
                                      ,[entityresponseTime] = @reponseTime
                                      ,[entitygmtTime] = @tradeTime WHERE Id={recordId}";
                }
                SqlParameter[] param =
                {
                    new SqlParameter("@requestTime", System.Data.SqlDbType.DateTime2),
                    new SqlParameter("@reponseTime", System.Data.SqlDbType.DateTime2),
                    new SqlParameter("@tradeTime", System.Data.SqlDbType.DateTime2), 
                };
                param[0].Value = requestTime;
                param[1].Value = reponseTime;
                param[2].Value = tradeTime; 



                if (SqlHelper.ExecuteNonQuery(GetCon(), CommandType.Text, strSql, param) > 0)
                {
                    AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付结果成功", billNo);
                    return true;
                }
                else
                {
                    AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付结果失败", billNo);
                    return false;
                }
            }
            catch (Exception ex)
            {
                AiLogger.Instance.WriteLog($@"{billNo}-->{plateNo}-->更新支付结果异常", billNo);
                AiLogger.Instance.Error($@"{billNo}-->{plateNo}-->" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 转换无感支付
        public async Task<bool> ChangeBillWG(long stationId, string billNo, long opuserId, string opuserName, string opuserTureName)
        {
            try
            {
                SqlParameter[] param =
               {
                    new SqlParameter("@billno", System.Data.SqlDbType.VarChar),
                    new SqlParameter("@stationId", System.Data.SqlDbType.BigInt),
                    new SqlParameter("@UpuserId", System.Data.SqlDbType.BigInt),
                    new SqlParameter("@UpuserName", System.Data.SqlDbType.VarChar),
                    new SqlParameter("@UpuserTrueName", System.Data.SqlDbType.NVarChar),
                };
                param[0].Value = billNo;
                param[1].Value = stationId;
                param[2].Value = opuserId;
                param[3].Value = opuserName;
                param[4].Value = opuserTureName;



                return SqlHelper.ExecuteNonQuery(GetCon(), CommandType.StoredProcedure, "o_InsertDigityPayWG", param) > 0;

            }
            catch (Exception ex)
            {
                LogHelper.Logger.Error("ChangeBillWG-->" + ex.Message);
                return false;
            }
        }
        #endregion
    }
}
